/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * Copyright (C) 2020 - 2022 EmDev LLC
 * ==========
 * 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.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.producer.executor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.core.producer.api.EntaxyProducerService;
import ru.entaxy.platform.core.producer.api.ProducerResult;
import ru.entaxy.platform.core.producer.api.ProducerResult.CommandResult;
import ru.entaxy.platform.core.producer.api.ProducingCommandExecutor;

public abstract class AbstractCommandExecutor implements ProducingCommandExecutor {

	private static final Logger log = LoggerFactory.getLogger(AbstractCommandExecutor.class);
	
	public static String SKIP_INSTRUSTION = "skip";
	public static String PRINT_OUTPUT_INSTRUSTION = "printOutput";
	
	protected EntaxyProducerService entaxyProducerService;
	
	protected String id;
	protected List<String> requiredPredecessors = new ArrayList<>();
	protected List<String> descendants = new ArrayList<>();
	protected List<Class<?>> acceptedInputClasses = new ArrayList<>();
	protected List<Class<?>> producedOutputClasses = new ArrayList<>();
	
	protected boolean isPrintOutput = false;
	
	protected Map<String, Object> instructions;
	
	protected AbstractCommandExecutor(EntaxyProducerService entaxyProducerService) {
		this.entaxyProducerService = entaxyProducerService;
		if (this.getClass().isAnnotationPresent(CommandExecutor.class)) {
			CommandExecutor commandExecutorAnnotation = this.getClass().getAnnotation(CommandExecutor.class);
			this.id = commandExecutorAnnotation.id();
			this.requiredPredecessors = Arrays.asList(commandExecutorAnnotation.predecessors());
			this.descendants = Arrays.asList(commandExecutorAnnotation.descendants());
			this.acceptedInputClasses  = Arrays.asList(commandExecutorAnnotation.inputs());
			this.producedOutputClasses = Arrays.asList(commandExecutorAnnotation.outputs());
		}
	}
	
	@Override
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Override
	public List<String> getRequiredPredecessors() {
		return requiredPredecessors;
	}

	public void setRequiredPredecessors(List<String> requiredPredecessors) {
		this.requiredPredecessors = requiredPredecessors;
	}

	@Override
	public List<String> getDescendants() {
		return descendants;
	}
	
	public void setDescendants(List<String> descendants) {
		this.descendants = descendants;
	}

	@Override
	public List<Class<?>> getAcceptedInputClasses() {
		return acceptedInputClasses;
	}

	public void setAcceptedInputClasses(List<Class<?>> acceptedInputClasses) {
		this.acceptedInputClasses = acceptedInputClasses;
	}

	@Override
	public List<Class<?>> getProducedOutputClasses() {
		return this.producedOutputClasses;
	}
	
	public void setProducedOutputClasses(List<Class<?>> producedOutputClasses) {
		this.producedOutputClasses = producedOutputClasses;
	}

	@Override
	public ProducerResult execute(ProducerResult currentResult, Map<String, Object> instructions) {
		CommandResult cr = new CommandResult(getId());
		this.instructions = instructions;
		setPrintOutput(instructions);
		if (isSkipped(instructions))
			cr.skipped = true;
		else	
			try {
				cr.result = doExecute(currentResult, cr, instructions);
			} catch (Exception e) {
				log.error("Error executing [" + getId() + "]", e);
				cr.exception(e).result(false);
			}
		currentResult.addCommandResult(cr);
		return currentResult;
	}

	protected void setPrintOutput(Map<String, Object> parameters) {
		if (parameters.containsKey(PRINT_OUTPUT_INSTRUSTION)) {
			Object val = parameters.get(PRINT_OUTPUT_INSTRUSTION);
			if (val == null)
				return;
			if (val instanceof Boolean)
				this.isPrintOutput = (Boolean)val;
		}
	}
	
	protected void printOutput(String message) {
		if (this.isPrintOutput)
			// OUTPUT TO CONSOLE
			System.out.println(message);
	}
	
	protected boolean isSkipped(Map<String, Object> parameters) {
		if (!parameters.containsKey(SKIP_INSTRUSTION))
			return false;
		Object obj = parameters.get(SKIP_INSTRUSTION);
		if (obj instanceof Boolean)
			return (Boolean)obj;
		if (obj instanceof String)
			return "true".equalsIgnoreCase((String)obj);
		if (obj instanceof Number)
			return ((Number)obj).intValue() > 0;
		return false;
	}
	
	protected abstract boolean doExecute(ProducerResult currentResult
			, CommandResult commandResult
			, Map<String, Object> instructions) throws Exception;
	
}
