package com.liquidnet.commons.lang.util;

import org.apache.logging.log4j.util.PropertiesUtil;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;

public class SqlMapping {
    private static final String sqlMapDir = "sqlmap";
    private static Map<String, Object> sqlPropertiesMap = new HashMap<>();

    static {
        try {
            URL url = PropertiesUtil.class.getClassLoader().getResource(sqlMapDir);
            if (null != url) {
                File file = new File(url.getFile());
                if (file.exists() && file.isDirectory()) {
                    File[] files = file.listFiles();
                    for (File f : files) {
                        if (f.isFile() && f.getName().endsWith("properties")) {
                            Properties props = PropertiesLoaderUtils.loadAllProperties(sqlMapDir.concat("/") + f.getName());
                            for (Object key : props.keySet()) {
                                String keyStr = key.toString();
                                String value = props.getProperty(keyStr);
                                sqlPropertiesMap.put(keyStr, value);
                            }
                        }
                    }
                }
            }
            System.out.printf("sqlPropertiesMap init count: %s\n", sqlPropertiesMap.size());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object get(String sql) {
        return sqlPropertiesMap.get(sql);
    }

    public static String get(String sql, Object... params) {
        LinkedList<String> sqls = new LinkedList<>();
        sqls.add(sqlPropertiesMap.get(sql).toString());
        LinkedList<Object[]> paramsList = new LinkedList<>();
        paramsList.add(params);
        LinkedList<Object[]>[] args = new LinkedList[]{paramsList};

        SqlMessage sqlMessage = SqlMessage.getInstance();
        sqlMessage.setSqls(sqls);
        sqlMessage.setArgs(args);
        return JsonUtils.toJson(sqlMessage);
    }

    public static String get(String sql, LinkedList<Object[]> paramsList) {
        LinkedList<String> sqls = new LinkedList<>();
        sqls.add(sqlPropertiesMap.get(sql).toString());
        LinkedList<Object[]>[] args = new LinkedList[]{paramsList};

        SqlMessage sqlMessage = SqlMessage.getInstance();
        sqlMessage.setSqls(sqls);
        sqlMessage.setArgs(args);
        return JsonUtils.toJson(sqlMessage);
    }

    public static String get(LinkedList<String> sqls, LinkedList<Object[]> paramsList) {
        LinkedList<Object[]>[] args = new LinkedList[]{paramsList};

        SqlMessage sqlMessage = SqlMessage.getInstance();
        sqlMessage.setSqls(sqls);
        sqlMessage.setArgs(args);
        return JsonUtils.toJson(sqlMessage);
    }
}
