package net.northking.cctp.upperComputer.driver.harmony.ui;


import net.northking.cctp.upperComputer.driver.protocol.packet.ICommandData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;

/**
 * UI元素节点
 */
public class UiComponent implements ICommandData, XMLEntity {
    public UiAttribute attributes;
    public ArrayList<UiComponent> children = new ArrayList<>();

    public UiComponent() {

    }

    public UiComponent(DataInput dataInput) throws IOException {
        buildFromInput(dataInput);
    }

    @Override
    public String toString() {
        return "UiComponent{" +
                "attributes=" + attributes +
                ", children=" + children +
                '}';
    }

    @Override
    public void buildFromInput(DataInput dataInput) throws IOException {
        attributes = new UiAttribute(dataInput);
        int childCount = dataInput.readInt();
        for (int i = 0; i < childCount; i++) {
            children.add(new UiComponent(dataInput));
        }
    }

    @Override
    public void encodeToOutput(DataOutput dataOutput) throws IOException {
        attributes.encodeToOutput(dataOutput);
        dataOutput.writeInt(children.size());
        for (UiComponent child : children) {
            child.encodeToOutput(dataOutput);
        }
    }

    @Override
    public Node createXMLElement(Document document) {
        String type = attributes.getType();
        if (type == null) {
            type = "Root";
        }
        String text = attributes.getText();
        if (text == null) {
            text = "";
        }
        Element element = document.createElement(type);
        element.setAttribute("id", attributes.getId());
        element.setAttribute("x", String.valueOf(attributes.getBoundRect().getLeft()));
        element.setAttribute("y", String.valueOf(attributes.getBoundRect().getTop()));
        element.setAttribute("width", String.valueOf(attributes.getBoundRect().getWidth()));
        element.setAttribute("height", String.valueOf(attributes.getBoundRect().getHeight()));
        element.setAttribute("text", text);
        for (UiComponent child : children) {
            Node childElement = child.createXMLElement(document);
            element.appendChild(childElement);
        }
        return element;
    }
}
