/*-
 * ~~~~~~licensing~~~~~~
 * blueprint-generator
 * ==========
 * 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.blueprint.generator;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

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

import ru.entaxy.base.generator.template.Template;
import ru.entaxy.base.generator.template.TemplateAwareGenerator;
import ru.entaxy.base.generator.template.TemplateImpl;
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;

@Component(service = {BlueprintGenerator.class}, immediate = true)
public class BlueprintGeneratorImpl implements BlueprintGenerator {

    private static final Logger LOG = LoggerFactory.getLogger(BlueprintGeneratorImpl.class);
    private static final String SYSTEM_NAME = "systemName";

    @Reference(cardinality = ReferenceCardinality.MANDATORY)
    protected TemplateService templateService;
    
    @Override
    public Blueprint createBlueprint(URL templateUrl, String templateName, String systemName, Map<String, String> params)
            throws Exception {
    	TemplateImpl template = new TemplateImpl();
    	template.setTemplateName(templateName);
    	template.setTemplateLocation(templateUrl.toString());
    	template.setType("ftl");
        return createBlueprintWithTemplate(template, systemName, params);
    }

    @Override
    public Blueprint createBlueprint(String templateName, String systemName, Map<String, String> params) throws Exception {
    	Template template = templateService.getTemplateById(templateName);
    	if (template == null) {
    		LOG.error("Template not found: [{}]", templateName);
    		// TODO throw exception
    		return null;
    	}
        return createBlueprintWithTemplate(template, systemName, params);
    }

    protected Blueprint createBlueprintWithTemplate(ru.entaxy.base.generator.template.Template template,
    		String systemName, Map<String, String> params) throws Exception {
    	TemplateAwareGenerator generator = GeneratorFactory.createGenerator(template);
    	if (generator == null) {
    		LOG.error("Generator not found for template: [{}]", template.getId());
    		// TODO throw exception
    		return null;
    	}
    	addSystemParam(params, systemName);
    	Map<String, Object> parameters = new HashMap<>();
    	parameters.putAll(params);
    	Generated result = generator.generate(template,parameters);
    	if ((result == null) || (result.getObject() == null)) {
    		LOG.error("Generator returned null for template: [{}]", template.getId());
    		// TODO throw exception
    		return null;
    	}
    	if (!Generated.GENERATED_TYPE_BLUEPRINT.equals(result.getType())) {
			LOG.error("Generator returned type [{}], while [{}] is expected for template: [{}]"
					, result.getType()
					, Generated.GENERATED_TYPE_BLUEPRINT
					, template.getId());
			// TODO throw exception
			return null;
    	}
    	Blueprint blueprint = new Blueprint(template.getTemplateName(), result.getObject().toString().getBytes());
    	blueprint.getProperties().putAll(result.getProperties());
    	blueprint.getProperties().put("template.name", template.getTemplateName());
    	blueprint.getProperties().put("template.id", template.getId());
    	blueprint.getProperties().put("template.type", template.getType());
    	return blueprint;
    }
    
    private void addSystemParam(Map<String, String> params, String systemName) {
        params.put(SYSTEM_NAME, systemName);
    }

}
