package com.yutou.jianr_mg.Tools;

import com.yutou.jianr_mg.Application;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * Created by 58381 on 2018/2/18.
 */

public class ConfigUtils {
    public static final String collection="collection";
    public static final String token="token";
    public static final String uid="uid";
    public static final String user="user";

    private static ConfigUtils config;
    private static final String configPath=Application.application.getFilesDir().getAbsolutePath();
    private JSONObject json;
    public static ConfigUtils init(){
        if(config==null){
            config=new ConfigUtils();
        }
        return config;
    }

    public ConfigUtils() {
        json=read();
    }
    private JSONObject read(){
        File file=new File(configPath+"/appConfig.json");
        if(file.exists()){
            try {
                BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                String tmp,str="";
                while ((tmp=reader.readLine())!=null){
                    str+=tmp;
                }
                reader.close();
                return new JSONObject(str);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return initConfig();
        }else{
            try {
                new File(configPath).mkdirs();
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return initConfig();
        }
    }
    private JSONObject initConfig(){
        JSONObject json=new JSONObject();
        try {
            json.put("token","");
            json.put("uid",0);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return json;
    }
    public boolean save(String key, Object value){
        try {
            File file=new File(configPath+"/appConfig.json");
            if(!file.exists()){
                file.createNewFile();
            }
            json.put(key,value);
            PrintWriter writer=new PrintWriter(file);
            writer.println(json.toString());
            writer.flush();
            writer.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public Object load(String key){
        try{
            return  json.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public void printConfig(){
        Log.i("读取配置文件",json.toString());
    }
}
