package com.chinaweal.aiccs.aiccs.business.rules.init;

import com.chinaweal.aiccs.aiccs.business.rules.parsexml.ParseRuleXML;
import com.chinaweal.aiccs.aiccs.business.rules.model.RuleModel;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.dom4j.DocumentException;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/1/29 16:38
 **/
@Slf4j
public class InitRules {

    private static Map<String, RuleModel> ruleModelMap;

    public InitRules(String dirPath) {
        parseWorkFlowXML(dirPath);
    }

    public void parseWorkFlowXML(String dirPath) {
        try {
            List<File> files = getAllFiles(dirPath);
            Map<String, RuleModel> _ruleModelMap = new HashMap<String, RuleModel>();
            RuleModel ruleModel;
            for (File file : files) {
                ruleModel = ParseRuleXML.parseXML(file);
                if (_ruleModelMap.put(ruleModel.getDefinedname(), ruleModel) != null) {
                    throw new BusinessException(file.getName() + "中的definedname和别的定义文件有冲突，请检查。");
                }
            }
            ruleModelMap = Collections.unmodifiableMap(_ruleModelMap);
        } catch (DocumentException e) {
            throw new BusinessException(e);
        } catch (IOException e) {
            throw new BusinessException(e);
        }
    }

    public static Map<String, RuleModel> getRuleModels() {
        if (ruleModelMap == null) {
            throw new BusinessException("工作流规则文件尚未初始化，请检查配置文件。");
        }
        return ruleModelMap;
    }

    private List<File> getAllFiles(String dirPath) throws IOException {
        URL resource = this.getClass().getResource(dirPath);
        List<File> files = new ArrayList<>();
        if (resource != null) {
            File directory = new File(resource.getFile());
            List<File> fileList = getFile(directory, files);
            if (CollectionUtils.isEmpty(fileList)) {
                log.warn("配置了工作流，但是没有工作流规则文件。");
            }
        } else {
            log.warn("配置了工作流，但是没有工作流规则文件。");
        }
        return files;
    }

    private List<File> getFile(File directory, List<File> files) {
        if (directory.isDirectory()) {
            File[] filesarr = directory.listFiles();
            if (ArrayUtils.isNotEmpty(filesarr)) {
                for (File file : filesarr) {
                    if (file.isDirectory()) {
                        getFile(file, files);
                    } else {
                        files.add(file);
                    }
                }
            }
        }
        return files;
    }
}
