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.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * @author fukai
 * ClassPath模式下的加载器
 */
@Component("esClassLoader")
public class EsClassPathLoader 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";
                Resource resource = new ClassPathResource(filePath);
                try (Reader commonReader = new InputStreamReader(resource.getInputStream());) {
                    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";
        Resource resource = new ClassPathResource(filePath);
        try (Reader reader = new InputStreamReader(resource.getInputStream())) {
            String curScript = IOUtils.toString(reader);
            if (EsConstant.VUE_TERMINAL.equals(envDespVo.getTerminal())) {
                return curScript;
            } else {
                return common_js + "\n" + curScript;
            }
        } catch (IOException e) {
            throw new RuntimeException("fail to read " + scriptName + ".js");
        }
    }

    @Override
    public String getCurPath(String path) {
        return "classpath:"+path;
    }
}
