package cn.teammodel.utils;

import cn.teammodel.common.ErrorCode;
import cn.teammodel.config.exception.ServiceException;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.InputStreamReader;
import java.io.Reader;

public class FileUtil {

    /**
     * 读取文件信息
     * @param file
     * @return
     */
    public static String readFile(File file) {
        StringBuilder sb = new StringBuilder();
        try {
            FileReader fileReader = new FileReader(file);
            Reader reader = new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8);
            int ch = 0;
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            return  sb.toString();
        }catch (IOException e)
        {
            throw new ServiceException(ErrorCode.SYSTEM_ERROR.getCode(), e.getMessage());
        }
    }

    /**
     * 根据key获取json
     * @param filepath 文件路径
     * @param key json的key
     * @return
     */
    public static Object getJSONByKey(String filepath, String key){
        String text =  FileUtil.getFileText(filepath);
        JSONObject object = new JSONObject();
        if (StringUtils.isNoneBlank(text)){
            object = parseObject(text);
        }
        return object.get(key);
    }

    /**
     * 将json 字符串转换为json对象
     */
    public static JSONObject parseObject(String text) {
        return JSONObject.parseObject(text);
    }

    /**
     * 获取文件内文本
     * @param filepath
     * @return
     */
    public static String getFileText(String filepath){
        StringBuffer sb = new StringBuffer();
        try{
            ClassPathResource classPathResource = new ClassPathResource(filepath);
            Reader reader = new InputStreamReader(classPathResource.getInputStream());
            int ch = 0;
            while ((ch = reader.read())!=-1){
                sb.append((char)ch);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString().replaceAll("\r\n","").replaceAll(" ","");
    }
}
