/*-
 * ~~~~~~licensing~~~~~~
 * ftl-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.esb.platform.runtime.base.connecting.generator.ftl;

import static freemarker.template.Configuration.SQUARE_BRACKET_INTERPOLATION_SYNTAX;
import static freemarker.template.Configuration.SQUARE_BRACKET_TAG_SYNTAX;

import java.io.IOException;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.cache.URLTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import ru.entaxy.base.generator.template.TemplateAwareGenerator;
import ru.entaxy.base.generator.template.TemplateImpl;
import ru.entaxy.base.generator.template.exception.TemplateNotFound;
import ru.entaxy.esb.platform.runtime.base.connecting.generator.AbstractSelfPublishGenerator;
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.GeneratorService;
import ru.entaxy.esb.platform.runtime.base.connecting.generator.factory.GeneratorFactory;

@Component(
        service = {GeneratorService.class},
        property = {GeneratorService.PROP_GENERATOR_TYPE + "=" + FTLGenerator.GENERATOR_NAME},
        immediate = true)
public class FTLGenerator extends AbstractSelfPublishGenerator<FTLGenerator>
        implements Generator, TemplateAwareGenerator {

    public final static String GENERATOR_NAME = "ftl";

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

    public static final String PROP_TEMPLATE_NAME = "template.name";
    public static final String PROP_TEMPLATE_PATH = "template.path";

    private static final String ATTR_GENERATED_TYPE = "generated.type";

    private static final String FTL_EXTENSION = ".ftl";
    private static final String XML_EXTENSION = ".xml";

    private static final String DEFAULT_TEMPLATE_PATH = "/template/";

    // private BlueprintGenerator blueprintGenerator;
    private ru.entaxy.base.generator.template.Template template;

    @Activate
    public void activate() {
        GeneratorFactory.register(FTLGenerator.GENERATOR_NAME, this);
    }

    @Deactivate
    public void deactivate() {
        GeneratorFactory.unregister(GENERATOR_NAME);
    }

    @Override
    public List<String> getSupportedTemplateTypes() {
        return Arrays.asList(new String[] {"ftl"});
    }

    @Override
    public Generated generate(ru.entaxy.base.generator.template.Template template, Map<String, Object> properties)
            throws Exception {
        return generateForTemplate(template, properties);
    }

    @Override
    public Generated generate(Map<String, Object> properties) throws Exception {
        prepareTemplate(properties);
        return generateForTemplate(template, properties);
    }

    @Override
    public boolean isGeneratable(Map<String, Object> properties) throws Exception {
        prepareTemplate(properties);
        if (template == null)
            return false;
        URL templateURL = template.getTemplateLocation() == null
                ? FrameworkUtil.getBundle(FTLGenerator.class).getEntry(DEFAULT_TEMPLATE_PATH)
                : template.getTemplateLocation();
        try {
            Template temp = getTemplateByFullName(templateURL, template.getTemplateFullName());
            return (temp != null);
        } catch (Exception e) {
            return false;
        }
    }

    public Generated generateForTemplate(ru.entaxy.base.generator.template.Template template,
            Map<String, Object> properties) throws Exception {

        URL templateURL = template.getTemplateLocation() == null
                ? FrameworkUtil.getBundle(FTLGenerator.class).getEntry(DEFAULT_TEMPLATE_PATH)
                : template.getTemplateLocation();
        try {
            return doGenerate(
                    templateURL,
                    template.getTemplateFullName(),
                    properties);
        } catch (Exception e) {
            log.error("Error generating for template [" + template.getId() + "]", e);
            throw e;
        }
    }


    protected static class Enricher {
        Generated origin;

        Map<String, Object> properties = new HashMap<>();

        String extraPrefix = "extra.";

        public Enricher(Generated origin) {
            this.origin = origin;
        }

        public Enricher cleanOrigin() {
            this.origin.getProperties().clear();
            return this;
        }

        public Enricher property(String name, Object value) {
            properties.put(name, value);
            return this;
        }

        public Enricher properties(Map<String, Object> properties) {
            this.properties.putAll(properties);
            return this;
        }

        public Enricher extraPrefix(String extraPrefix) {
            this.extraPrefix = extraPrefix;
            return this;
        }

        public Enricher extra(String name, Object value) {
            properties.put(extraPrefix + name, value);
            return this;
        }

        public Enricher extras(Map<String, Object> properties) {
            for (Map.Entry<String, Object> entry : properties.entrySet())
                this.properties.put(extraPrefix + entry.getKey(), entry.getValue());
            return this;
        }

        public Generated get() {
            this.origin.getProperties().putAll(this.properties);
            this.origin.getProperties().put("_extraPrefix", extraPrefix);
            return this.origin;
        }
    }

    protected static Enricher enrich(Generated origin) {
        return new Enricher(origin);
    }

    private Generated doGenerate(URL templateUrl, String templateFullName, Map<String, Object> params)
            throws IOException, TemplateException, TemplateNotFound {
        Template temp = getTemplateByFullName(templateUrl, templateFullName);
        Object value = temp.getCustomAttribute(FTLGenerator.ATTR_GENERATED_TYPE);
        String type = null == value ? null : value.toString();
        log.debug("--TEMPLATE--\n" + templateUrl.toString() + templateFullName + "\ngenerated.type: "
                + (null == value ? Generated.GENERATED_TYPE_UNKNOWN : value.toString()));
        try (StringWriter writer = new StringWriter()) {
            temp.process(params, writer);
            return enrich(Generated.create(type, writer.toString()))
                    .properties(params)
                    .extraPrefix("generator.")
                    .extra("templateUrl", templateUrl)
                    .extra("templateFullName", value)
                    .get();
        }
    }


    protected void prepareTemplate(Map<String, Object> generationProperties) {
        if (this.template != null)
            return;

        Map<String, Object> finalProperties = new HashMap<>();
        finalProperties.putAll(initialProperties);
        finalProperties.putAll(generationProperties);

        TemplateImpl temp = new TemplateImpl();
        temp.setBundleContext(
                (BundleContext) finalProperties.getOrDefault(Generator.PROP_TARGET_BUNDLE_CONTEXT,
                        FrameworkUtil.getBundle(FTLGenerator.class).getBundleContext()));
        temp.setTemplateName((String) finalProperties.getOrDefault(PROP_TEMPLATE_NAME,
                (String) finalProperties.getOrDefault(Generator.PROP_USAGE_TYPE, "root")));
        temp.setPath((String) finalProperties.getOrDefault(PROP_TEMPLATE_NAME, DEFAULT_TEMPLATE_PATH));

        temp.setTemplateFullName(temp.getTemplateFileName() + FTL_EXTENSION);

        this.template = temp;

    }

    private Generated doGenerate(URL templateUrl, String templateName, String systemName, Map<String, String> params)
            throws IOException, TemplateException, TemplateNotFound {
        Template temp = getTemplateByName(templateUrl, templateName);
        Object value = temp.getCustomAttribute(FTLGenerator.ATTR_GENERATED_TYPE);
        String type = null == value ? null : value.toString();
        log.info("--BLUEPRINT--\n" + templateUrl.toString() + templateName + "\ngenerated.type: "
                + (null == value ? Generated.GENERATED_TYPE_UNKNOWN : value.toString()));
        try (StringWriter writer = new StringWriter()) {
            temp.process(params, writer);
            return Generated.create(type, writer.toString());
        }
    }

    private Template getTemplateByFullName(URL templateUrl, String templateFullName)
            throws IOException, TemplateNotFound {
        Configuration cfg = getConfiguration(templateUrl);
        return cfg.getTemplate(templateFullName);
    }

    private Template getTemplateByName(URL templateUrl, String templateName) throws IOException, TemplateNotFound {
        return getTemplateByFullName(templateUrl, templateName + FTL_EXTENSION);
    }

    private Configuration getConfiguration(URL templateUrl) throws TemplateNotFound {
        Configuration freemarkerConfig = new Configuration();
        freemarkerConfig.setObjectWrapper(new DefaultObjectWrapper());
        freemarkerConfig.setLocalizedLookup(false);
        freemarkerConfig.setTemplateLoader(getURLTemplateLoader(templateUrl));
        freemarkerConfig.setInterpolationSyntax(SQUARE_BRACKET_INTERPOLATION_SYNTAX);
        freemarkerConfig.setTagSyntax(SQUARE_BRACKET_TAG_SYNTAX);
        //no localization of number and boolean
        freemarkerConfig.setNumberFormat("computer");
        freemarkerConfig.setBooleanFormat("c");
        return freemarkerConfig;
    }

    private URLTemplateLoader getURLTemplateLoader(URL templateUrl) {
        return new URLTemplateLoader() {
            @Override
            protected URL getURL(String templateName) {
                try {
                    if (templateName.contains(":"))
                        return new URL(templateName);
                    return new URL(templateUrl + templateName);
                } catch (MalformedURLException e) {
                    // skip printing typical error
                    // while searching for template
                    if ((templateUrl != null) || (!"root.ftl".equals(templateName)))
                        log.error(e.getMessage(), e);
                }
                return null;
            }
        };
    }

    @Deprecated
    public void setTemplate(ru.entaxy.base.generator.template.Template template) {
        this.template = template;
    }

}
