package org.ts.ddcs.DataTemplate;

import org.ts.ddcs.DataRelayDatabaseProcesser.DataRelayDatabaseProcesserInterface;
import org.ts.ddcs.DataSaveProcesser.DataSaveProcesserInterface;
import org.ts.ddcs.log.LogHelper;

import java.util.ArrayList;

/**
 * @author dylan
 */
public class DataTemplateLine {

    private ArrayList<TemplateLineNode> templateLine = new ArrayList<>();

    public void Stream(byte[] data) {
        if (templateLine.size()>0) {
            int index = 0;
            while (true) {
                TemplateLineNode node = templateLine.get(index);
                if (node.getDataTemplate().Macth(data)) {
                    LogHelper.info("macth :" + node.getDataTemplate().GetName());
                    node.getDataTemplate().Stream();
                    break;
                }
                index++;
                if (templateLine.size() == index) {
                    break;
                }
            }
        }
    }

    public TemplateLineNode MacthTemplate() {
        for (int i = 0; i < templateLine.size(); i++) {
            TemplateLineNode node = templateLine.get(i);
            if (node.getDataTemplate().Macth()) {
                return node;
            }
        }
        return null;
    }

    public void cloneTemplate(TemplateSet template) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        try {
            TemplateLineNode node = new TemplateLineNode();
            Class class1 = Class.forName(template.getDataSaveProcess());
            Object obj1 = class1.newInstance();
            if (obj1 instanceof DataSaveProcesserInterface) {
                node.setDataSaveProcess((DataSaveProcesserInterface) obj1);
            } else {
                throw new ClassNotFoundException();
            }

            Class class2 = Class.forName(template.getDataTemplate());
            Object obj2 = class2.newInstance();
            if (obj2 instanceof DataTemplateInterface) {
                node.setDataTemplate((DataTemplateInterface) obj2);
            } else {
                throw new ClassNotFoundException();
            }

            String relayProcess = template.getDataRelayProcess();
            if (null != relayProcess && relayProcess.length() > 0) {
                Class class3 = Class.forName(relayProcess);
                Object obj3 = class3.newInstance();
                if (obj3 instanceof DataRelayDatabaseProcesserInterface) {
                    node.setDataRelayProcess((DataRelayDatabaseProcesserInterface) obj3);
                } else {
                    throw new ClassNotFoundException();
                }
            }
            node.setTemplateSet(template);
            node.getDataTemplate().Init(template);
            templateLine.add(node);
        } catch (Exception e) {
            LogHelper.error(e);
            throw e;
        }
    }
}
