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