import { Container, Sprite } from "../../engine/2d/display";
import { TextField } from "../../engine/2d/text";
import Texture from "../../engine/2d/texture/Texture";

import { Event } from "../../engine/2d/events";
import { TEXT_ALIGN } from "../../engine/2d/const";
import { Graphics } from "../../engine/2d/graphics";
import { RES } from "../RES";
import { layers } from "../views/layers";


let inited = false;
let _waiting: Waiting;
let _parent: Container
const initWaiting = () => {
    if (!inited) {
        inited = true;
        const waiting = new Waiting();
        _parent = layers.topLayer;
        _waiting = waiting;
    }
}
/**
 * 显示菊花圈
 * @param msg 尽量三个字
 */
export const showWaiting = (msg?: string) => {
    initWaiting();
    _waiting.show(msg)
    _parent.addChild(_waiting);
}

/**
 * 隐藏菊花圈
 */
export const hideWaiting = () => {
    _parent.removeChild(_waiting);
}

export const destroyWaiting = () => {
    if (inited && !_waiting.destroyed) {
        _waiting.destroy();
        _waiting = null;
        _parent = null;
    }
}


/**
 * 菊花圈
 */
class Waiting extends Container {
    msg: TextField;
    constructor() {
        super();
        //阻止事件用
        var bg: Graphics = new Graphics();
        bg.beginFill(0x000000, 0);
        bg.drawRect(0, 0, 750, 1624);
        bg.endFill();
        this.addChild(bg);
        //圆角矩形背景
        var rectBgTexture: Texture = RES.getRes("waitingBg.png")
        var rectBg = new Sprite(rectBgTexture);
        rectBg.x = (layers.stageWidth - rectBgTexture.width) / 2;
        rectBg.y = 486;//高度看需求，到时可以居中
        this.addChild(rectBg);
        var rotTexture: Texture = RES.getRes("waitingRot.png")
        let rot = new Sprite(rotTexture);
        rot.x = (layers.stageWidth - rotTexture.width) / 2;
        rot.y = 533;
        rot.anchorX = rotTexture.width / 2;
        rot.anchorY = rotTexture.height / 2;
        this.addChild(rot);
        let count = 0;
        rot.addEventListener(Event.ENTER_FRAME, () => {
            count++;
            if (count % 30 == 0) rot.rotation += 45;
        }, this)
        this.msg = new TextField();
        this.msg.x = 295;
        this.msg.y = 611;
        this.msg.textWidth = 160
        this.msg.textAlign = TEXT_ALIGN.CENTER;
        this.msg.size = 26
        this.msg.fillColor = "#ffffff";
        this.addChild(this.msg);
    }

    show(msg: string = "加载中") {
        this.msg.text = msg;
    }

    destroy() {
        super.destroy();
        this.msg = null;
    }
}

