package com.brilliance.isc.common.validator.es.support.impl;

import com.brilliance.isc.common.validator.es.factory.ScriptTemplateFactory;
import com.brilliance.isc.common.validator.es.support.IEsLoader;
import com.brilliance.isc.common.validator.es.utils.EsConstant;
import com.brilliance.isc.common.validator.es.vo.EnvDespVo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * 从文件中加载JS文件
 *
 * @author fukai
 */
@Component("esPathLoader")
public class EsFilePathLoader implements IEsLoader {

    @Autowired
    private ScriptTemplateFactory scriptTemplateFactory;

    static String COMMON_JS = "";

    public String loadCommonJS() {
        if (COMMON_JS.isEmpty()) {
            synchronized (this) {
                if (!COMMON_JS.isEmpty()) {
                    return COMMON_JS;
                }
                //简单通过文件加载返回
                String scriptName = "common";
                String filePath = scriptTemplateFactory.getPath() + "/" + scriptName + ".js";
                try (Reader commonReader = new FileReader(filePath)) {
                    String common_js = IOUtils.toString(commonReader);
                    if(!scriptTemplateFactory.isDebugMode()) {
                        COMMON_JS = common_js;
                    }
                    return common_js;
                } catch (IOException e) {
                    throw new RuntimeException("fail to read " + scriptName + ".js");
                }
            }
        }else{
            return COMMON_JS;
        }
    }


    @Override
    public String loadEsScript(EnvDespVo envDespVo) {
        String common_js = loadCommonJS();
        String scriptName = envDespVo.getScriptName();
        //从文件中加载
        String filePath = scriptTemplateFactory.getPath() + "/" + scriptName + ".js";
        try (Reader reader = new FileReader(filePath)) {
            String curScript = IOUtils.toString(reader);
            if (EsConstant.VUE_TERMINAL.equals(envDespVo.getTerminal())) {
                return curScript;
            } else {
                return common_js + "\n" + curScript;
            }
        } catch (Exception e) {
            throw new RuntimeException("fail to read " + scriptName + ".js");
        }
    }

    @Override
    public String saveBakScript(EnvDespVo envDespVo,String source) {
//        String scriptName = envDespVo.getScriptName();
//        //从文件中加载
//        String filePath = templateFactory.getPath() + "/" + scriptName + "_bak.js";
//        try {
//            FileUtils.write(new File(filePath),source,"utf-8");
//        } catch (IOException e) {
//            throw new RuntimeException("save bak file error:"+filePath,e);
//        }
//        return String.format("load('%s')",filePath);
        return source;
    }
}
