package com.gyee.runeconomy.controller.agc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.stereotype.Component;

import java.io.*;
import java.lang.reflect.Type;

/**
 * 配置文件读取
 *
 * @author xysn
 */
@Component
public class FileService {
    /**
     * 从json格式文件中获取对象
     *
     * @param path 文件路径
     * @param type 对象类型
     * @param <T>  泛型
     * @return 返回对象
     */
    public <T> T getFromFile(String path, Type type) {
        String str = getStringFormFile(path);
        return JSON.parseObject(str, type);
    }

    /**
     * 从json格式文件中获取对象
     *
     * @param path 文件路径
     * @param type 对象类型
     * @param <T>  泛型
     * @return 返回对象
     */
    public <T> T getFromFile(String path, TypeReference<T> type) {
        String str = getStringFormFile(path);
        return JSON.parseObject(str, type);
    }

    /**
     * 从文件中获取字符串
     *
     * @param path 路径
     * @return 字符串
     */
    public String getStringFormFile(String path) {
        BufferedReader bufferedReader = null;
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            StringBuilder sb = new StringBuilder();
            String s = null;
            while ((s = bufferedReader.readLine()) != null) {
                sb.append(s);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert bufferedReader != null;
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    /**
     * 保存对象到文件中
     *
     * @param path 文件路径
     * @param obj  要保存的对象
     * @return 是否保存成功
     */
    public boolean saveObjectToFile(String path, Object obj) {
        BufferedWriter bufferedWriter = null;
        try {
            File file = new File(path);
            bufferedWriter = new BufferedWriter(new FileWriter(file));
            String str = "";
            if (obj instanceof String) {
                str = obj.toString();
            } else {
                str = JSON.toJSONString(obj);
            }
            bufferedWriter.write(str);
            bufferedWriter.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert bufferedWriter != null;
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
