/*-
 * ~~~~~~licensing~~~~~~
 * test-producers
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/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.EntaxyProducerService.INSTRUCTIONS;
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;
import ru.entaxy.platform.core.producer.executor.support.AbstractPrintOutputSupport;

public abstract class AbstractCommandExecutor extends AbstractPrintOutputSupport 
		implements ProducingCommandExecutor {

	private static final Logger log = LoggerFactory.getLogger(AbstractCommandExecutor.class);
	
	public static int DEFAULT_MAX_COUNT = 15;
	
	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 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);
		int maxCount = getMaxCount(instructions);
		int currentCount = getCurrentCount(instructions);
		printOutput("\n\n\t== " + getId().toUpperCase() + " == #" + currentCount + " of " + maxCount + " ==\n");
		if (isSkipped(instructions)) {
			cr.skipped = true;
			printOutput(" :: SKIPPED ");			
		} else {	
			try {
				cr.result = doExecute(currentResult, cr, instructions);
			} catch (Exception e) {
				log.error("Error executing [" + getId() + "]", e);
				cr.exception(e).result(false);
			}
			if (currentCount >= maxCount) {
				instructions.put(INSTRUCTIONS.SKIP, true);
				printOutput(" !! Max iteration count of [" + maxCount + "] is reached"
						+ "\n    futher iterations will be skipped ");
			} else {
				increaseCurrentCount(instructions);
			}
		}
		printOutput("\n\n\t== /" + getId().toUpperCase() + " == ");
		currentResult.addCommandResult(cr);
		return currentResult;
	}
	
	protected int getMaxCount(Map<String, Object> parameters) {
		int result = DEFAULT_MAX_COUNT;
		if (parameters.containsKey(INSTRUCTIONS.MAX_COUNT)) {
			Object val = parameters.get(INSTRUCTIONS.MAX_COUNT);
			try {
				result = ((Number)val).intValue(); 
			} catch (Exception e) {
				parameters.put(INSTRUCTIONS.MAX_COUNT, DEFAULT_MAX_COUNT);
			}
		}
		return result;
	}

	protected int getCurrentCount(Map<String, Object> parameters) {
		int result = 1;
		if (parameters.containsKey(INSTRUCTIONS.CURRENT_ITERATION)) {
			Object val = parameters.get(INSTRUCTIONS.CURRENT_ITERATION);
			try {
				result = (Integer)val; 
			} catch (Exception e) {
				parameters.put(INSTRUCTIONS.CURRENT_ITERATION, 1);
			}
		}
		return result;
	}

	protected int increaseCurrentCount(Map<String, Object> parameters) {
		int currentCount = getCurrentCount(parameters);
		currentCount++;
		parameters.put(INSTRUCTIONS.CURRENT_ITERATION, currentCount);
		return getCurrentCount(parameters);
	}
	
	protected boolean isSkipped(Map<String, Object> parameters) {
		if (!parameters.containsKey(INSTRUCTIONS.SKIP))
			return false;
		Object obj = parameters.get(INSTRUCTIONS.SKIP);
		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;
	
}
