/*-
 * -\-\-
 * Spotify Styx Common
 * --
 * Copyright (C) 2016 Spotify AB
 * --
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * -/-/-
 */

package com.spotify.styx.state;

import com.spotify.styx.model.Event;
import com.spotify.styx.monitoring.TracingProxy;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Interface defining all state machine outputs generated by {@link RunState}.
 * An {@link OutputHandler} implementation handles (takes action) on {@link RunState}
 * transitions into a new {@link RunState.State}.
 *
 * <p>Note: All {@link OutputHandler} implementations should be idempotent (or harmless) as they might be invoked
 * multiple times (at-least-once) for a single {@link RunState} transition.
 */
@FunctionalInterface
public interface OutputHandler {

  /**
   * Handles (takes action) on {@link RunState} transitions into a new {@link RunState.State}.
   *
   * @param state       the state to transition into
   * @param eventRouter can be used to route event to to the corresponding active {@link RunState} based on
   *                    the {@link Event#workflowInstance()} key of the event.
   */
  void transitionInto(RunState state, EventRouter eventRouter);

  static OutputHandler fanOutput(Collection<OutputHandler> outputHandlers) {
    return (state, eventRouter) -> outputHandlers.forEach(
        outputHandler -> outputHandler.transitionInto(state, eventRouter));
  }

  static OutputHandler tracing(OutputHandler outputHandler) {
    return TracingProxy.instrument(OutputHandler.class, outputHandler);
  }

  static List<OutputHandler> tracing(Collection<OutputHandler> outputHandlers) {
    return outputHandlers.stream().map(OutputHandler::tracing).collect(Collectors.toList());
  }

  static OutputHandler mdcDecorating(OutputHandler delegate) {
    return new MDCDecoratingHandler(delegate);
  }
}
