package com.slodon.b2b2c.ueditor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * 读取json文件，转为对象
 */
@Slf4j
public class JsonFileReadUtil {

    /**
     * json文件转为对象
     *
     * @param filePath 文件位置
     * @return
     */
    public static JSONObject jsonFileToObject(String filePath) {
        try {
            String file = readFile(filePath);
            return JSON.parseObject(file);
        } catch (IOException e) {
            log.error("配置文件读取无效");
            throw new RuntimeException();
        }
    }

    /**
     * 读取json文件
     *
     * @param path 文件路径
     * @return json字符串
     * @throws IOException
     */
    private static String readFile(String path) throws IOException {
        StringBuilder builder = new StringBuilder();
        try {

            InputStreamReader reader = new InputStreamReader(Objects.requireNonNull(JsonFileReadUtil.class.getClassLoader().getResourceAsStream(path)), "UTF-8");
            BufferedReader bfReader = new BufferedReader(reader);

            String tmpContent = null;

            while ((tmpContent = bfReader.readLine()) != null) {
                builder.append(tmpContent);
            }
            bfReader.close();
        } catch (UnsupportedEncodingException e) {
            // 忽略
        }
        return filter(builder.toString());
    }

    /**
     * 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
     *
     * @param input
     * @return
     */
    private static String filter(String input) {
        return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
    }
}
