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


import net.northking.cctp.upperComputer.driver.protocol.packet.ICommandData;

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

public class UiRect implements ICommandData {
    private int left, top, right, bottom;

    /**
     * Rect文本，例如 [0,0][1216,2688]
     *
     * @param text
     */
    public UiRect(String text) {
        if (text == null) return;
        if (text.length() < 10) throw new IllegalArgumentException("无法解析的UiRect字符串: " + text);
        try {
            left = Integer.parseInt(text.substring(1, text.indexOf(",")));
            top = Integer.parseInt(text.substring(text.indexOf(",") + 1, text.indexOf("][")));
            right = Integer.parseInt(text.substring(text.indexOf("][") + 2, text.lastIndexOf(",")));
            bottom = Integer.parseInt(text.substring(text.lastIndexOf(",") + 1, text.length() - 1));
        } catch (Exception e) {
            throw new IllegalArgumentException("无法解析UiRect字符串", e);
        }
    }

    public UiRect(DataInput dataInput) throws IOException {
        this.buildFromInput(dataInput);
    }

    public int getLeft() {
        return left;
    }

    public int getTop() {
        return top;
    }

    public int getRight() {
        return right;
    }

    public int getBottom() {
        return bottom;
    }

    public int getWidth() {
        return right - left;
    }

    public int getHeight() {
        return bottom - top;
    }

    @Override
    public String toString() {
        return "[" + left +
                "," + top +
                "][" + right +
                "," + bottom +
                ']';
    }

    @Override
    public void buildFromInput(DataInput dataInput) throws IOException {
        left = dataInput.readInt();
        top = dataInput.readInt();
        right = dataInput.readInt();
        bottom = dataInput.readInt();
    }

    @Override
    public void encodeToOutput(DataOutput dataOutput) throws IOException {
        dataOutput.writeInt(left);
        dataOutput.writeInt(top);
        dataOutput.writeInt(right);
        dataOutput.writeInt(bottom);
    }
}
