/*-
 * ~~~~~~licensing~~~~~~
 * blueprint-generator
 * ==========
 * Copyright (C) 2020 - 2021 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.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);
    }

}
