package com.brilliance.isc.doc.utils;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.brilliance.isc.common.context.SpringEnvContext;
import com.brilliance.isc.common.tools.service.ObjectStroeToolService;
import com.brilliance.isc.doc.constant.DocConstant;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;

/**
 * 维护模板
 */
@org.springframework.context.annotation.Configuration
public class TemplateFactory {
    private static Configuration configuration;
    private static Logger logger = LoggerFactory.getLogger(TemplateFactory.class);
    private static Template DEMO_TEMPLATE;
    private static String DEMO_TEMPLATE_NAME = "DEMO.html";
    private static String DEMO_PDF_TEMPLATE_NAME = "DEMO.pdf";
    private static InputStream DEMO_INPUTSTREAM;

    @Value("${sstf.doc.templatepath:sstf/doc/templates}")
    private String templateBasePath;
    @Resource
    private ObjectStroeToolService objectStoreService;

    @PostConstruct
    public void init() throws IOException {
        configuration = new Configuration();
        configuration.setClassLoaderForTemplateLoading(TemplateFactory.class.getClassLoader(), DocConstant.BASE_TEMPLATE_FOLDER);
        ////云存储获取面函模板（开发阶段，使用上面的方法）
        //configuration.setTemplateLoader(new RealtimeFileTemplateLoader(templateBasePath,objectStoreService));
        try {
            DEMO_TEMPLATE = configuration.getTemplate(DEMO_TEMPLATE_NAME);
            DEMO_TEMPLATE.setEncoding("UTF-8");
            DEMO_INPUTSTREAM = TemplateFactory.class.getClassLoader().getResourceAsStream(DocConstant.BASE_TEMPLATE_FOLDER + "/" + DEMO_PDF_TEMPLATE_NAME);
        } catch (IOException e) {
            logger.warn("DEMO加载失败：", e);
        }
    }

    public static Template getTemplate(String templatePath, String lang) {
        try {
            templatePath = getNewTemplatePath(templatePath, lang);
            Template template = configuration.getTemplate(templatePath);
            template.setEncoding("UTF-8");
            return template;
        } catch (IOException e) {
            logger.error("{}读取失败:", e);
        }
        return DEMO_TEMPLATE;
    }

    public static InputStream getPdfTemplateStream(String templatePath, String lang) {
        templatePath = getNewTemplatePath(templatePath, lang);
        //InputStream inputStream = TemplateFactory.class.getClassLoader().getResourceAsStream(DocConstant.BASE_TEMPLATE_FOLDER+"/"+templatePath);
        //云存储获取面函模板（开发阶段，使用上面的方法）
        InputStream inputStream = getResourceAsStream(templatePath);
        if (inputStream == null) {
            logger.error("{}模板文件读取失败:", templatePath);
            return DEMO_INPUTSTREAM;
        }
        return inputStream;
    }

    /**
     * 将语言项，拼进模板名称中
     *
     * @param templatePath
     * @param lang
     * @return
     */
    private static String getNewTemplatePath(String templatePath, String lang) {
        int idx = templatePath.lastIndexOf(".");
        templatePath = templatePath.substring(0, idx) + "_" + lang.toUpperCase() + templatePath.substring(idx);
        return templatePath;
    }

    /**
     * 模板查找顺序
     * <ol>
     *     <li>从对象存储查找</li>
     *     <li>从类路径下查找</li>
     * </ol>
     */
    public static InputStream getResourceAsStream(String name) {
        ObjectStroeToolService objectStoreService2 = SpringEnvContext.getBean(ObjectStroeToolService.class);
        String path = new StringBuffer("sstf/data/doc/templates/").append(name).toString();
        if (objectStoreService2.isExistObjectFile(path)) {
            try {
                return new FileInputStream(objectStoreService2.getObjectFile(path));
            } catch (Exception e) {
                logger.error("从对象存储获取pdf模板失败", e);
            }
        }
        String classPath = new StringBuffer(DocConstant.BASE_TEMPLATE_FOLDER).append("/").append(name).toString();
        try {
            return TemplateFactory.class.getClassLoader().getResourceAsStream(classPath);
        } catch (Exception e) {
        }
        logger.error("没查找到pdf模板文件{}", name);
        return null;
    }
}
