/*-
 * ~~~~~~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.base.objects.factory.impl;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.osgi.service.component.annotations.CollectionType;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.base.generator.template.Template;
import ru.entaxy.base.generator.template.TemplateService;
import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated;
import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generator;
import ru.entaxy.esb.platform.runtime.base.connecting.generator.factory.GeneratorFactory;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory.OutputInfo;
import ru.entaxy.platform.base.objects.factory.EntaxyFactory.SCOPE;

@Component(immediate = true, service = {GenerationHelper.class})
public class GenerationHelper {

	private static final Logger log = LoggerFactory.getLogger(GenerationHelper.class);

	@Reference(cardinality = ReferenceCardinality.MANDATORY, collectionType = CollectionType.SERVICE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
	protected volatile TemplateService templateService;
	
	public Generated generateForFactory(EntaxyFactory factory, String outputType, SCOPE scope, Map<String, Object> parameters) throws Exception {
		
		log.debug("GENERATING for factory [" + factory.getFactoryId() + "]");
		log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: PARAMETERS \n"
				 + parameters.entrySet().stream().map(e -> e.getKey() + ":" + (null==e.getValue()?"null":e.getValue()))
				 .collect(Collectors.toList())
				 .stream().collect(Collectors.joining(", "))
				);
		
		OutputInfo outputInfo = factory.getOutputByType(outputType);
		
		if (outputInfo == null) {
			// @TODO throw Exception
			log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: output [{}] not found", outputType);
			return null;
		}
			
		if (!outputInfo.getScopes().contains(scope.label)) {
			// @TODO throw Exception
			log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: scope [{}] not supported", scope.label);
			return null;
		}
			
		// try to generate via GeneratorFactory
		log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: TRY via GeneratorFactory");
		Generator g = GeneratorFactory.createGenerator(outputInfo.getGenerator(), outputInfo.getConfig());
		if (g.isGeneratable(parameters)) {
			log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: generating");
			return g.generate(parameters);
		} else {
			log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: NOT generatable");			
		}
		
		// try to generate via TemplateService
		log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: TRY via TemplateService");
		List<String> candidates = new LinkedList<>();
		candidates.add(factory.getFactoryId() + "." + outputType + "." + scope.label);
		candidates.add(factory.getFactoryId() + "." + outputType);
		if (outputInfo.isDefault()) {
			candidates.add(factory.getFactoryId() + ".default." + scope.label);
			candidates.add(factory.getFactoryId() + ".default");
			candidates.add(factory.getFactoryId() + "." + scope.label);
			candidates.add(factory.getFactoryId());
		}
		
		log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: CANDIDATES : ["
					+ candidates.stream().collect(Collectors.joining(";"))
					+ "]"
				);
		
		for (String candidate: candidates) {
			Template t = templateService.getTemplateById(candidate); 
			if (t != null) {
				log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: FOUND TEMPLATE : ["
						+ candidate	+ "]");
				Generated result = GeneratorFactory.createGenerator(t).generate(t, parameters);
				return result;
			} else {
				log.debug("GENERATING for factory [" + factory.getFactoryId() + "] :: NOT FOUND TEMPLATE : ["
						+ candidate	+ "]");
			}
		}
		return null;
	}

	public TemplateService getTemplateService() {
		return templateService;
	}

	public void setTemplateService(TemplateService templateService) {
		this.templateService = templateService;
	}
	
}
