package com.brilliance.mda.runtime.mda.config;

import cn.hutool.core.lang.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class IniConfig {
    private static Logger logger = LoggerFactory.getLogger(IniConfig.class);
    private static Map<String,IniConfig> iniConfigMap = new HashMap<>();

    public static String getIniConfig(String iniName,String block,String key){
        //返回默认币种
        if(key!=null && (key.equalsIgnoreCase("SysCurrency")
                        ||key.equalsIgnoreCase("RateBaseCurrency")
                        ||key.equalsIgnoreCase("CURRENCY"))){
            return "EUR";
        }
        //后续需要添加在trade.ini中
        if(iniConfigMap.containsKey(iniName.toUpperCase())) {
            Assert.notNull(key);
            return iniConfigMap.get(iniName.toUpperCase()).get(block.toUpperCase(), key.toUpperCase());
        }
        return "";
    }

    private Map<String, Map<String,String>> data = new HashMap<>();

    public Map<String,String> getBlock(String block){
        return data.get(block);
    }

    public String get(String block,String key){
        if(data.containsKey(block))
            return data.get(block).get(key);
        return null;
    }

    public void set(String block,String key,String value){
        if(!data.containsKey(block))
            data.put(block,new HashMap<>());
        data.get(block).put(key,value);
    }

    public static IniConfig loadIniFile(String name,InputStream inputStream,String charset){
        IniConfig config = new IniConfig();

        try(BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,charset))) {
            String str,block = null;
            while ((str = br.readLine()) != null){
                if(!StringUtils.hasLength(str)){
                    continue;
                }
                if(str.indexOf('[')==0){
                    if (str.indexOf(']') < 0){
                        block = str.substring(1);
                    }else{
                        block = str.substring(1,str.indexOf(']'));
                    }
                    block = block.toUpperCase();
                }else if(str.indexOf('=')>-1){
                    if (str.indexOf(';') == 0){
                        continue;
                    }
                    if (str.indexOf(';') > 0){
                        str = str.substring(0, str.indexOf(';'));
                    }
                    String[] ary = str.trim().split("=");
                    String val = "";
                    if (ary.length >= 2){
                        val = ary[1];
                    }
                    config.set(block,ary[0].trim(),val.trim());
                }
            }
        } catch (Exception e) {
            logger.error(String.format("解析INI配置[%s]错误！", name));
            System.exit(-1);
        }
        return config;
    }

    public static void loadIni(File file){
        IniConfig config = new IniConfig();

        try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gb2312"))) {
            String str="",block="";
            while ((str = br.readLine()) != null){
                if(StringUtils.isEmpty(str))
                    continue;
                if(str.indexOf('[')==0){
                    if (str.indexOf(']') < 0){
                        block = str.substring(1);
                    }else{
                        block = str.substring(1,str.indexOf(']'));
                    }
                    block = block.toUpperCase();
                }else if(str.indexOf('=')>-1){
                    if (str.indexOf(';') == 0){
                        continue;
                    }
                    if (str.indexOf(';') > 0){
                        str = str.substring(0, str.indexOf(';'));
                    }
                    String[] ary = str.trim().split("=");
                    String val = "";
                    if (ary.length >= 2){
                        val = ary[1];
                    }
                    config.set(block,ary[0].trim().toUpperCase(),val);
                }
            }
        } catch (Exception e) {
            logger.error(String.format("解析INI配置[%s]错误！", file.getAbsolutePath()));
            System.exit(-1);
        }
        iniConfigMap.put(file.getName().toUpperCase(),config);
    }

    public static void loadIni(String name,InputStream inputStream){
        IniConfig config = new IniConfig();

        try(BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"))) {
            String str="",block="";
            while ((str = br.readLine()) != null){
                if(StringUtils.isEmpty(str))
                    continue;
                if(str.indexOf('[')==0){
                    if (str.indexOf(']') < 0){
                        block = str.substring(1);
                    }else{
                        block = str.substring(1,str.indexOf(']'));
                    }
                    block = block.toUpperCase();
                }else if(str.indexOf('=')>-1){
                    if (str.indexOf(';') == 0){
                        continue;
                    }
                    if (str.indexOf(';') > 0){
                        str = str.substring(0, str.indexOf(';'));
                    }
                    String[] ary = str.trim().split("=");
                    String val = "";
                    if (ary.length >= 2){
                        val = ary[1];
                    }
                    config.set(block,ary[0].trim().toUpperCase(),val);
                }
            }
        } catch (Exception e) {
            logger.error(String.format("解析INI配置[%s]错误！", name));
            System.exit(-1);
        }
        iniConfigMap.put(name.toUpperCase(),config);
    }


    public static Map<String, IniConfig> getIniConfigMap() {
        return iniConfigMap;
    }

    public Map<String, Map<String, String>> getData() {
        return data;
    }
}

