package org.ts.ddcs.DataTemplate;

import org.ts.ddcs.DataItemTemplate.DataItemTemplate;
import org.ts.ddcs.DataItemTemplate.DataItemTemplateInterface;
import org.ts.ddcs.Log.LogHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * 数据项模板处理链路
 * @author dylan
 */
public class DataItemTemplateLine {

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

    public void stream(byte[] data) {
        int index = 0;
        int orgLen = data.length;
        while (true) {
            ItemTemplateLineNode node = this.templateLine.get(index);
            data = node.getDataTemplate().Stream(data);
            if (data.length == 0) {
                break;
            }
            index++;
            if (this.templateLine.size() == index) {
                break;
            }
            int newLen = data.length;
            if (newLen != orgLen) {
                index = 0;
            }
            orgLen = newLen;
        }
    }

    public HashMap<String, DataItemTemplateInterface> MacthTemplate() {
        HashMap<String, DataItemTemplateInterface> macthItem = new HashMap<>();
        for (int i = 0; i < this.templateLine.size(); i++) {
            ItemTemplateLineNode node = this.templateLine.get(i);
            if (node.getDataTemplate().Macth()) {
                macthItem.put(node.getTemplateSet().getColumn(), node.getDataTemplate());
            }
        }
        return macthItem;
    }

    public void cloneItemTemplate(ItemTemplateSet template) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        try {
            ItemTemplateLineNode node = new ItemTemplateLineNode();
            Class class2 = Class.forName(template.getDataTemplate());
            Object obj2 = class2.newInstance();
            if (obj2 instanceof DataItemTemplateInterface) {
                node.setDataTemplate( (DataItemTemplateInterface) obj2);
            } else {
                throw new ClassNotFoundException();
            }
            node.setTemplateSet(template);
            node.getDataTemplate().Init(template);
            this.templateLine.add(node);
        } catch (Exception e) {
            LogHelper.error(e);
            throw e;
        }
    }
}
