/*-
 * ~~~~~~licensing~~~~~~
 * connection-producing
 * ==========
 * 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.base.objects.connection.producing.adapters;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

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

import ru.entaxy.platform.base.objects.factory.EntaxyFactory.OutputInfo;
import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.platform.base.objects.EntaxyObject;
import ru.entaxy.platform.base.objects.connection.producing.ConnectionProducer;
import ru.entaxy.platform.base.objects.factory.EntaxyFactoryException;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.core.producer.api.EntaxyWrappedFactory;
import ru.entaxy.platform.core.producer.wrapper.AbstractFactoryWrapper.GenerationProcessor;

public class AdapterWrapperGenerationProcessor implements GenerationProcessor {

	private static final Logger log = LoggerFactory.getLogger(AdapterWrapperGenerationProcessor.class);
	
	public static final String PATH_PARAMETER_OUTPUT = "pathParameter";
	public static final String EXPRESSION_ATTRIBUTE = "expression";

	public static final String PROPERTY_CONFIGURATION_PID = "configurationPid";
	public static final String PID_PREFIX = "ru.entaxy.esb.connection.";
	
	protected GenerationProcessor preBefore, preAfter, postBefore, postAfter;
	
	@Override
	public void preGenerate(EntaxyWrappedFactory wrappedFactory, String outputType, String scope, String objectType,
			Map<String, Object> parameters) throws EntaxyFactoryException {
		if (preBefore != null)
			preBefore.preGenerate(wrappedFactory, outputType, scope, objectType, parameters);
		
		// add pathParameter based on config
		if (!parameters.containsKey(PATH_PARAMETER_OUTPUT)) {
			log.debug(">> ADDING " + PATH_PARAMETER_OUTPUT);
			OutputInfo outputInfo = wrappedFactory.getOutputByType(PATH_PARAMETER_OUTPUT);
			if (outputInfo != null) {
				log.debug(">> FOUND OUTPUT " + PATH_PARAMETER_OUTPUT 
						+ ", CONFIG IS "
						+ (outputInfo.getConfig()!=null?"NOT ":"")
						+ "NULL");
				if (outputInfo.getConfig()!=null)
					log.debug(outputInfo.getConfig().toString());
				String expression = outputInfo.getConfig()!=null
						?outputInfo.getConfig().getOrDefault(EXPRESSION_ATTRIBUTE, "").toString()
						:"";
				log.debug(">> EXPRESSION: [" + expression + "]");
				if (CommonUtils.isValid(expression) && expression.startsWith("${")) {
					String lookup = expression.substring(2, expression.lastIndexOf("}"));
					log.debug(">> LOOKUP: [" + lookup + "]");
					if (CommonUtils.isValid(lookup))
						parameters.put(PATH_PARAMETER_OUTPUT, parameters.getOrDefault(lookup, ""));
				}
			}
		}
		// set configurationPid to 'ru.entaxy.esb.connection.' + name.replace('-', '.')
		String name = parameters.getOrDefault("name", UUID.randomUUID()).toString();
		name = name.replace("-", ".");
		String configurationPid = PID_PREFIX + name;
		parameters.put(PROPERTY_CONFIGURATION_PID, configurationPid);
		
		// remove 'name' from properties
		Map<String, Object> properties = (Map<String, Object>)parameters.get(EntaxyObject.FIELDS.PROPERTIES);
		properties.remove(ConnectionProducer.PROPERTY_NAME);
		
		// copy all the parameters to 'connection'
		Map<String, Object> copy = new HashMap<>(parameters);
		parameters.put("connection", copy);

		// System.out.println("\n\n===>>>\n:" + parameters.toString() + "\n\n");
		
		log.debug("RESULT PARAMETERS :: " + parameters.toString());
		
		if (preAfter != null)
			preAfter.preGenerate(wrappedFactory, outputType, scope, objectType, parameters);
	}

	@Override
	public void postGenerate(EntaxyWrappedFactory wrappedFactory, String outputType, String scope, String objectType,
			Map<String, Object> parameters, Generated generated) throws EntaxyFactoryException {
		
		if (postBefore != null)
			postBefore.postGenerate(wrappedFactory, outputType, scope, objectType, parameters, generated);
			

		if (postAfter != null)
			postAfter.postGenerate(wrappedFactory, outputType, scope, objectType, parameters, generated);
	
	}	
	
	public void setPreBefore(GenerationProcessor preBefore) {
		this.preBefore = preBefore;
	}

	public void setPreAfter(GenerationProcessor preAfter) {
		this.preAfter = preAfter;
	}

	public void setPostBefore(GenerationProcessor postBefore) {
		this.postBefore = postBefore;
	}

	public void setPostAfter(GenerationProcessor postAfter) {
		this.postAfter = postAfter;
	}
	
	
	
}
