package com.ag.secp.platform.microkernel;

import com.ag.psamathe.api.Module;
import com.ag.psamathe.api.ModuleConfig;
import com.ag.psamathe.api.ModuleLoader;
import com.ag.psamathe.api.ModuleManager;
import com.ag.psamathe.api.impl.SpringModule;
import com.ag.until.StrUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Component
public class MoudleMangerProcess {

    @Autowired
    private ModuleLoader moduleLoader;
    @Autowired
    private ModuleManager moduleManager;


    /**
     * 部署模式
     *
     * @param
     */
    public Object deployModule(JSONObject jsonObject, HttpServletResponse response, HttpServletRequest request, String beanName, String methodName) throws Exception {
        long on = System.currentTimeMillis();
        Module module = moduleManager.find("demo");
        ApplicationContext context = ((SpringModule)module).getApplicationContext();
        long end = System.currentTimeMillis();
        System.out.println("module find times::"+(end-on));
        //doAction执行了Action接口的execute方法
        Object result = null;
        try {
            result = context.getBean(StrUtil.firstToLower(beanName));
        }catch (Exception ex){
            throw new RuntimeException("beanName不正确, 请检查!["+beanName+"]");
        }
        Method method = result.getClass().getMethod(methodName, JSONObject.class, HttpServletResponse.class, HttpServletRequest.class);
        return method.invoke(result, jsonObject, response, request);

    }

    /**
     * 读取jar包的开发者模式
     *
     * @param
     */
    public Object developerForJar(JSONObject jsonObject, HttpServletResponse response, HttpServletRequest request, String beanName, String methodName) throws Exception {
        ModuleConfig config = buildModuleConfig();
        long on = System.currentTimeMillis();
        Module module = moduleLoader.load(config);
        ApplicationContext context = ((SpringModule)module).getApplicationContext();
        long end = System.currentTimeMillis();
        System.out.println("module load times::"+(end-on));
        //doAction执行了Action接口的execute方法
        Object result = null;
        try {
            result = context.getBean(StrUtil.firstToLower(beanName));
        }catch (Exception ex){
            throw new RuntimeException("beanName不正确, 请检查!["+beanName+"]");
        }
        Method method = result.getClass().getMethod(methodName, JSONObject.class, HttpServletResponse.class, HttpServletRequest.class);

        return ReflectionUtils.invokeMethod(method, result, jsonObject,response,request);
     //   method.invoke(result, jsonObject, response, request);

    }


    public ModuleConfig buildModuleConfig() {

        List<URL> urls = new ArrayList<>();
        List<String> scanPackages = new ArrayList<>();
        //URL demoModule = null;
        try {
            String propPath = Thread.currentThread().getContextClassLoader().getResource("")+"a.properties";
            // win 把5换成 6
            Properties property = getProperty(propPath.substring(6, propPath.length()));
            // win   demoModule = new URL("file:\\" + property.get("dynamicJarPath"));
            //demoModule = new URL("file:" + property.get("dynamicJarPath"));
            String[] arrs = property.get("dynamicJarPath").toString().split(",");
            for (String arr : arrs){
                if (StrUtil.isEmpty(arr)){
                    continue;
                }
                urls.add(new URL("file:" + arr));
            }
            String[] scans = property.get("scanPackages").toString().split(",");
            for (String arr : scans){
                if (StrUtil.isEmpty(arr)){
                    continue;
                }
                scanPackages.add(arr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModuleConfig moduleConfig = new ModuleConfig();
        //通过该方法构建的配置都是使用注解形式扫描bean的
        //String scanBase = "com.ag.dynamicmodule";
        //Map<String, Object> properties = ;
        moduleConfig.setName("demo");
        moduleConfig.setVersion("0.1");
        moduleConfig.setModuleUrl(urls);
        //moduleConfig.setNeedUnloadOldVersion(false);
        moduleConfig.setOverridePackages(scanPackages);
//        moduleConfig.addScanPackage(scanPackage);
        //Map<String, Object> properties = new HashMap<>();
        //properties.put("url", "127.0.0.1");
        //moduleConfig.setProperties(properties);
        /*moduleConfig.withEnabled(enabled).withVersion(version).withOverridePackages(ImmutableList.of(
                scanPackage)).withProperties(properties);*/
        //  demoModule = Thread.currentThread().getContextClassLoader().getResource(JARSLINK_MODULE_DEMO);

        //moduleConfig.setOverridePackages(ImmutableList.of(scanPackage));

        //moduleConfig.setEnabled(enabled);
        /*if (StrUtil.isNotEmpty(version)){
            moduleConfig.setVersion(version);
        }*/

        //properties.put("url", "127.0.0.1");
        //

        return moduleConfig;
    }

    public Properties getProperty(String path) {
        Properties properties = new Properties();
        try {
            InputStreamReader in = new InputStreamReader(new FileInputStream(path), "UTF-8");
            properties.load(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return properties;

    }

}
