package com.ssj.kmt.utils;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author: chchen
 * @Description
 * @Date Create in 11:12 2020/6/2
 * @Modified By
 */
public class JSONFileUtil {
    private static final Logger logger = LoggerFactory.getLogger(JSONFileUtil.class);

    /**
     * 读取json文件
     * @param jsonFilePath json 绝对文件名
     * @return 返回json字符串
     */
    public static String readJSONFile(String jsonFilePath) {
//        logger.info("————开始读取" + jsonFilePath + "文件————");
        FileReader fr = null;
        BufferedReader br = null;
        try {
            File jsonFile = FileUtils.getFile(jsonFilePath);
            fr = new FileReader(jsonFile);
            br = new BufferedReader(fr);
            StringBuffer sb = new StringBuffer();
            String line; // 用来保存每行读取的内容
            line = br.readLine(); // 读取第一行
            while (line != null) { // 如果 line 为空说明读完了
                sb.append(line); // 将读到的内容添加到 buffer 中
                sb.append("\n"); // 添加换行符
                line = br.readLine(); // 读取下一行
            }
            fr.close();
            br.close();
//            logger.info("————读取" + jsonFile.getPath() + "文件结束!————");
            return sb.toString();
        } catch (Exception e) {
            logger.error("读取题目文件异常", e);
            return null;
        } finally {
            try {
                if (fr != null){
                    fr.close();
                }
            } catch (Exception e){
                logger.error("关闭流异常", e);
            }
            try {
                if (br != null){
                    br.close();
                }
            } catch (Exception e){
                logger.error("关闭流异常", e);
            }
        }
    }

    /**
     * 读取网络json文件
     * @param urlPath
     * @return
     */
    public static String readNetWorkJSONFile (String urlPath){
        InputStreamReader isReader = null;
        BufferedReader reader = null;
        try {
            StringBuffer buffer = new StringBuffer(); //文件字符串
            int HttpResult; // 服务器返回的状态

            URL url =new URL(urlPath); // 创建URL
            URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
            urlconn.connect();
            HttpURLConnection httpconn =(HttpURLConnection)urlconn;
            HttpResult = httpconn.getResponseCode();
            if(HttpResult != HttpURLConnection.HTTP_OK) {
                logger.error("无法连接到", HttpResult);
            } else {
                isReader = new InputStreamReader(urlconn.getInputStream(),"UTF-8");
                reader = new BufferedReader(isReader);
                String line; // 用来保存每行读取的内容
                line = reader.readLine(); // 读取第一行
                while (line != null) { // 如果 line 为空说明读完了
                    buffer.append(line); // 将读到的内容添加到 buffer 中
                    buffer.append(" "); // 添加换行符
                    line = reader.readLine(); // 读取下一行
                }
            }
            return buffer.toString();
        } catch (IOException e) {
            logger.error("读取题目文件异常", e);
            return null;
        } finally {
            try {
                if (isReader != null){
                    isReader.close();
                }
            } catch (Exception e){
                logger.error("关闭流异常", e);
            }
            try {
                if (reader != null){
                    reader.close();
                }
            } catch (Exception e){
                logger.error("关闭流异常", e);
            }
        }
    }

    /**
     * 保存json文件
     * @param filePath
     * @param content
     */
    public static void saveJSONFile (String filePath, String content) {
        FileWriter fileWriter = null;
        BufferedWriter bw = null;
        try {
            //文件夹不存在时创建文件夹
            String dirPath = filePath.substring(0,filePath.lastIndexOf("/"));
            File dir = new File(dirPath);
            if (!dir.exists()){
                dir.mkdirs();
            }

            //文件不存在时创建文件
            File file = new File(filePath);
            if(!file.exists()){
                file.createNewFile();
            }
            fileWriter = new FileWriter(file);
            bw = new BufferedWriter(fileWriter);
            bw.write(content);
            bw.close();
        } catch (Exception e) {
            logger.error("题目文件保存异常", e);
        } finally {
            try {
                if (fileWriter != null){
                    fileWriter.close();
                }
            } catch (Exception e){
                logger.error("关闭流异常", e);
            }
            try {
                if (bw != null){
                    bw.close();
                }
            } catch (Exception e){
                logger.error("关闭流异常", e);
            }
        }
    }
}
