package com.yutou.tools.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.*;

/**
 * 配置和参数
 */
public class ConfigTools {
    public static final String CONFIG="config.json";
    public static final String DATA="data.json";
    public static final String SQLITE="sqlite.json";
    static {
        try {
            File file=new File(CONFIG);
            if(!file.exists()){
                file.createNewFile();
            }
            file=new File(DATA);
            if(!file.exists()){
                file.createNewFile();
            }
            file=null;
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    public static Object load(String type,String key){
        File file=new File(type);
        //System.out.println(type+"配置文件地址:"+file.getAbsolutePath());
        String src=readFile(file);
        if(src!=null){
            try {
                JSONObject json=JSONObject.parseObject(src);
                if(json==null){
                    json=new JSONObject();
                    saveFile(file,json.toJSONString());
                }
                return json.getOrDefault(key, "");
            }catch (Exception e){
                return "";
            }
        }
        return "";
    }
    public static boolean save(String type,String key,Object data){
        File file=new File(type);
        String src=readFile(file);
        if(src==null){
            src="{}";
        }
        JSONObject json=JSONObject.parseObject(src);
        json.put(key,data);
        saveFile(file,json.toJSONString());
        return false;
    }
    public static boolean saveFile(File file,String data){
        try {
            FileWriter writer=new FileWriter(file);
            writer.write(data);
            writer.flush();
            writer.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    public static String readFile(File file){
        try {
            BufferedReader reader=new BufferedReader(new FileReader(file));
            String tmp;
            StringBuilder str= new StringBuilder();
            while ((tmp=reader.readLine())!=null){
                str.append(tmp);
            }
            reader.close();
            return str.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
