package cn.com.ty.lift.ud.bpmConfig;

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

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

@Data
public class CaseBpmSer {
    private BpmChain ask;
    private BpmChain outAsk;

    private CaseBpmSer() {
    }

    private static CaseBpmSer instance;

    public static BpmNode getNode(int type, int status) {
        CaseBpmSer instance = getInstance();
        List<BpmNode> nodes = instance.getAsk().getNodes();
        if (type == 2){
            nodes = instance.getOutAsk().getNodes();
        }
        for (int i = 0; i < nodes.size(); i++) {
            BpmNode bpmNode = nodes.get(i);
            if (bpmNode.getStatus() == status) {
                return bpmNode;
            }
        }
        return null;
    }

    /**
     * 单利方法
     * @return
     */
    public static CaseBpmSer getInstance() {
        synchronized (instance){
            if (null == instance) {
                try {
                    String jsonStr = CaseBpmSer.parseJsonFileToObj();
                    instance = JSON.parseObject(jsonStr, CaseBpmSer.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return instance;
        }
    }

    /**
     * 解析json文件
     * @return
     * @throws IOException
     */
    private static String parseJsonFileToObj() throws IOException {
        File file = ResourceUtils.getFile("classpath:case-flow.json");
        /**
         * 文件有内容才去读文件
         */
        FileInputStream is = new FileInputStream(file);
        InputStreamReader streamReader = new InputStreamReader(is, "utf-8");
        BufferedReader reader = new BufferedReader(streamReader);
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        reader.close();
        is.close();

        String jsonStr = String.valueOf(stringBuilder);

        return jsonStr;
    }
}
