
class MTextEditor extends eui.Component implements eui.UIComponent {
    public get text(): string {
        if (typeof this.label == "undefined") {
            return "";
        } else {
            return this.label.text;
        }
    }
    public get width(): number {
        if (typeof this.label == "undefined") {
            return 0;
        } else {
            return this.label.width;
        }
    }
    public label: eui.Label;
    private editableText: eui.EditableText;
    private cursor: egret.Shape = new egret.Shape();
    private timer: number = 0;
    private blink: boolean = false;

    public onEditing: (text: number) => void;

    public setFocus() {
        this.editableText.setFocus();
    }

    createChildren() {
        if (typeof this.label == "undefined") return;

        let editableText = new eui.EditableText;
        editableText.height = 0;
        editableText.width = 0;
        this.addChild(editableText);
        editableText.text = this.label.text;
        this.editableText = editableText;

        this.cursor.graphics.beginFill(this.label.textColor);
        this.cursor.graphics.drawRect(0, 0, this.label.size * (3 / 40), this.label.height + this.label.size * (3 / 40));
        this.cursor.graphics.endFill();
        this.cursor.x = this.label.x + this.label.width;
        this.cursor.visible = false;
        this.cursor.y = this.label.y - (this.cursor.height / 2 - this.label.height / 2) - this.label.size * (3 / 40);
        this.addChild(this.cursor);

        this.addEventListener(egret.Event.ENTER_FRAME, this.onUpdate, this);

        this.addEventListener(egret.Event.REMOVED_FROM_STAGE, () => {
            this.removeEventListener(egret.Event.ENTER_FRAME, this.onUpdate, this);
        }, this);

        this.touchEnabled = true;
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, () => {
            this.editableText.setFocus();
        }, this);
        this.editableText.addEventListener(egret.Event.CHANGE, () => {
            this.label.text = this.editableText.text;
            this.cursor.x = this.label.x + this.label.width;
            this.onEditing && this.onEditing(this.label.textWidth);
        }, this);
        this.editableText.addEventListener(egret.FocusEvent.FOCUS_IN, () => {
            this.cursorBlink();
        }, this);
        this.editableText.addEventListener(egret.FocusEvent.FOCUS_OUT, () => {
            this.cursorVanish();
        }, this);
    }

    private onUpdate() {
        if (this.blink) {
            this.timer++;
            if (this.timer % 30 == 0) {
                this.cursor.visible = !this.cursor.visible;
            }
        }
    }

    private cursorBlink() {
        this.blink = true;
        this.cursor.visible = true;
        this.timer = 0;
    }

    private cursorVanish() {
        this.blink = false;
        this.cursor.visible = false;
    }
}

export default MTextEditor;