package com.cesgroup.cesmonitor.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * JSON工具类
 *
 * @author zhang.erwei
 * @version 1.0.0 2017年5月24日
 */
public class JSON {

    protected static Logger logger = LoggerFactory.getLogger(JSON.class);

    private static ExclusionStrategy myExclusionStrategy = new ExclusionStrategy() {

        @Override
        public boolean shouldSkipField(final FieldAttributes fa) {
            return false;
        }

        @Override
        public boolean shouldSkipClass(final Class<?> clazz) {
            return false;
        }
    };

    private static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").setExclusionStrategies(
        myExclusionStrategy).setPrettyPrinting()
        .create();

    /**
     * 字符串转对象
     *
     * @param json
     *            字符串
     * @param type
     *            类型
     * @return 对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T fromJson(final String json, final Type type) {
        return (T) gson.fromJson(json, type);
    }

    /**
     * 字符串转对象
     *
     * @param json
     *            字符串
     * @param cls
     *            对象类
     * @return 对象
     */
    public static <T> T fromJson(final String json, final Class<T> cls) {
        return gson.fromJson(json, cls);
    }

    /**
     * 对象转字符串
     *
     * @param obj
     *            对象
     * @return 字符串
     */
    public static String toJson(final Object obj) {
        return gson.toJson(obj);
    }

    /**
     * 从输入流读取字符串
     *
     * @param inputStream
     *            输入流
     * @return 字符串
     */
    public static String getStringFromFile(final InputStream inputStream) {
        InputStreamReader inputReader = null;
        BufferedReader bufferReader = null;
        StringBuffer sb = new StringBuffer();
        try {
            inputReader = new InputStreamReader(inputStream, "UTF-8");
            bufferReader = new BufferedReader(inputReader);
            // 读取一行
            String line = null;

            while ((line = bufferReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Throwable e) {
            throw new RuntimeException("无法读取配置文件", e);
        } finally {
            try {
                if (inputReader != null) {
                    inputReader.close();
                }
                if (bufferReader != null) {
                    bufferReader.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return sb.toString();

    }

    /**
     * 从输入文件取字符串
     *
     * @param file
     *            文件
     * @return 字符串
     */
    public static String getStringFromFile(final File file) {
        File newfile = new File(file.getAbsolutePath());
        if (!newfile.exists()) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        BufferedReader bufferReader = null;

        try {
            bufferReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            // 读取一行
            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Throwable e) {
            throw new RuntimeException("无法读取配置文件", e);
        } finally {
            try {
                if (bufferReader != null) {
                    bufferReader.close();
                }
                if (bufferReader != null) {
                    bufferReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();

    }

    /**
     * 保存字符串到文件中
     *
     * @param str
     *            字符串
     * @param filePath
     *            文件
     */
    public static void saveStringToFile(final String str, File filePath) {
        filePath = new File(filePath.getAbsolutePath());
        logger.info("保存到文件...：" + filePath.getAbsolutePath());
        OutputStreamWriter writer = null;
        try {
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            writer = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
            writer.write(str);
            logger.info("保存到文件：" + filePath.getAbsolutePath());
        } catch (Throwable e) {
            throw new RuntimeException("保存文件错误", e);
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("保存文件错误", e);
            }
        }
    }
}