package cn.freemud.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtil {
    public static final String DIR_PATH = "classpath:demodata/";

    public static final String FILE_SUFFIX = ".json";

    /** json数据**/
    public static Map<String, byte[]> jsonData = new HashMap<String, byte[]>();

    static {
        // 初始化数据
        initData();
    }
    /**
     * 初始化数据
     */
    public static void initData() {
        // 1.获取所有json文件名
        String[] fileNames = getFileList(DIR_PATH);
        // 2.读取json文件
        byte[] data = null;
        for(String fileName : fileNames) {
            data = readFromFile(fileName);
            //3.按文件名存放数据
            fileName = fileName.substring(0, fileName.indexOf('.'));
            jsonData.put(fileName, data);
        }
    }

    /**
     * 重新加载制定文件数据
     * @param fileName 文件名
     */
    public static void reloadData(String fileName) {
        byte[] data = readFromFile(fileName + FILE_SUFFIX);
        jsonData.put(fileName, data);
    }

    /**
     * 读取文件获取对象
     */
    public static<T> T getObjectFromFile(String fileName, Class<T> clazz) {
        byte[] data = jsonData.get(fileName);
        T result = JSON.parseObject(data, clazz);
        return result;
    }

    /**
     * 读取文件获取对象List
     */
    public static<T> List<T> getListFromFile(String fileName, Class<T> clazz) {
        byte[] data = jsonData.get(fileName);
        try {
            String s = new String(data, "utf-8");
            List<T> result = JSON.parseArray(s, clazz);
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获得文件夹下文件名列表
     */
    public static String[] getFileList(String path) {
        File a = null;
        String[] file = null;
        try {
            a = ResourceUtils.getFile(path);
            file = a.list();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if(file == null) {
            return null;
        } else {
            return file;
        }
    }

    /**
     * 根据文件路径得到文件内容
     */
    public static byte[] readFromFile(String fileName) {
        File file;
        FileInputStream fin;
        byte[] buf = null;
        try {
            file = ResourceUtils.getFile(DIR_PATH + fileName);
            fin = new FileInputStream(file);
            buf = new byte[fin.available()];
            fin.read(buf);
            fin.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buf;
    }
}
