package org.ts.ddcs.datatemplate;

import lombok.Data;
import org.ts.ddcs.log.LogHelper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.*;


/**
 * 数据报文模板管理主模块
 *
 * @author swp
 */
@Data
public class DataTemplateManager {

    private Map<String, List<Template>> templateMap = new HashMap(10);

    /**
     * 初始化模板
     *
     * @param dir       模板文档目录
     * @param templates 模板名称
     */
    public boolean init(String dir, String templates) {
        try {
            String[] list = templates.split(",");
            if (list.length > 0) {
                for (String t : list) {
                    String templateDoc = dir + File.separator + t.toLowerCase()+".xml";
                    File f = new File(templateDoc);
                    if (!f.exists()) {
                        return false;
                    }
                    List<Template> templateList = this.loadConfig(templateDoc);
                    this.templateMap.put(t, templateList);
                }
            }
            return true;
        } catch (Exception e) {
            LogHelper.error(e);
            return false;
        }
    }

    public Set<String> activeTemplate() {
        return templateMap.keySet();
    }

    public boolean hasTemplate(String agreement) {
        if (this.templateMap.containsKey(agreement)) {
            return true;
        }
        return false;
    }

    /**
     * 加载配置文件
     *
     * @param templates
     */
    private List<Template> loadConfig(String templates) throws DocumentException {
        List<Template> templateList = new LinkedList<>();
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File(templates));
        Element root = document.getRootElement();
        Element templateNode = root.element("Templates");
        List items = templateNode.elements("Item");
        for (Object o : items
        ) {
            Template template = new Template();
            Element e = (Element) o;
            String feature = e.element("Feature").getTextTrim();
            template.setFeature(feature);
            template.dataTemplate = e.element("DataTemplate").getTextTrim();
//            template.streamProcessor = e.element("StreamProcessor").getTextTrim();
//            List dataProcessors = e.elements("DataProcessor");
//            if (null != dataProcessors && dataProcessors.size() > 0) {
//                for (Object p : dataProcessors) {
//                    Element processor = (Element) p;
//                    String processorName = processor.getTextTrim();
//                    template.dataProcessor.add(processorName);
//                }
//            }
            template.templateName = e.element("TemplateName").getTextTrim();
            template.enable = e.element("Enable").getTextTrim();
//            List filters = e.elements("Filter");
//            for (Object f : filters) {
//                Element filter = (Element) f;
//                String filterName = filter.getTextTrim();
//                template.filter.add(filterName);
//            }
            templateList.add(template);
        }
        return templateList;

    }

    private Template cloneTemplate(Template template) {
        Template newTemplate = new Template();
        newTemplate.setDataTemplate(template.getDataTemplate());
        newTemplate.setTemplateName(template.getTemplateName());
        newTemplate.setFeatureWeight(template.getFeatureWeight());
        if (null != template.getFeatureKey()){
            byte[] featureKey = new byte[template.getFeatureKey().length];
            System.arraycopy(template.getFeatureKey(), 0, featureKey, 0, featureKey.length);
            newTemplate.setFeatureKey(featureKey);
        }
        if (null != template.getFeatureIndex()){
            byte[] featureIndex = new byte[template.getFeatureIndex().length];
            System.arraycopy(template.getFeatureIndex(), 0, featureIndex, 0, featureIndex.length);
            newTemplate.setFeatureIndex(featureIndex);
        }
        return newTemplate;
    }

    public List<Template> cloneTemplateLine(String templateKey) {
        if (this.templateMap.containsKey(templateKey)) {
            List<Template> enableTemplateLine = new LinkedList<>();
            List<Template> templateList = this.templateMap.get(templateKey);
            for (Template template : templateList
            ) {
                if ("1".equals(template.enable)) {
                    Template newTemplate = cloneTemplate(template);
                    enableTemplateLine.add(newTemplate);
                }
            }
            return enableTemplateLine;
        }
        return null;
    }


    /**
     * 创建模板实体类
     *
     * @return
     */
    public synchronized List<TemplateLineNode> cloneTemplateLineNode(String templateKey) {
        try {
            List<TemplateLineNode> templateLineNodes = new LinkedList<>();
            List<Template> templateList = this.templateMap.get(templateKey);
            for (Template template : templateList
            ) {
                if ("1".equals(template.enable)) {
                    TemplateLineNode templateLineNode = new TemplateLineNode();
                    templateLineNode.dataProcessor = template.newDataProcessorInstance();
                    templateLineNode.dataStreamProcessor = template.newDataStreamProcessorInstance();
                    templateLineNode.dataTemplate = template.newDataTemplateInstance();
                    templateLineNode.dataTemplate.setFeatureWeight(template.featureWeight);
                    templateLineNode.dataTemplate.setFeature(template.featureKey, template.featureIndex);
                    templateLineNode.filterList = template.createFilterLine();
                    templateLineNodes.add(templateLineNode);
                }
            }
            return templateLineNodes;
        } catch (Exception e) {
            LogHelper.error(e);
            return null;
        }
    }
}
