
import { RES } from "../RES";
import { layers } from "../views/layers";

import { showAlert } from ".";

let inited = false;
let _waiting: Waiting;
let _parent: FYGE.Container
const initWaiting = () => {
    if (!inited) {
        inited = true;
        const waiting = new Waiting();
        _parent = layers.topLayer;
        _waiting = waiting;
        //居中偏移
        var offX = (layers.stageWidth - 160/*_waiting.width*/) / 2;
        var offY = (layers.stageHeight - _waiting.height) / 2;
        //位置适配
        _waiting.x = layers.stageOffsetX - _parent.x + offX;
        _waiting.y = layers.stageOffsetY - _parent.y + offY;
        //阻止事件用
        var bg: FYGE.Graphics = new FYGE.Graphics()
            .beginFill(0x000000)
            .drawRect(-offX, -offY, layers.stageWidth, layers.stageHeight)
            .endFill();
        bg.alpha = 0;
        _waiting.addChildAt(bg, 0);
    }
}
/**
 * 显示菊花圈
 * @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 && !_waiting.destroyed) {
        _waiting.destroy();
        _waiting = null;
        _parent = null;
        inited = false;
    }
}


/**
 * 菊花圈，有机会重写，应该适应所有场景居中
 */
class Waiting extends FYGE.Container {
    msg: FYGE.TextField;
    constructor() {
        super();
        //圆角矩形背景
        var rectBgTexture: FYGE.Texture = RES.getRes("waitingBg.png")
        var rectBg = new FYGE.Sprite(rectBgTexture);
        this.addChild(rectBg);
        var rotTexture: FYGE.Texture = RES.getRes("waitingRot.png")
        let rot = new FYGE.Sprite(rotTexture);
        rot.x = (rectBgTexture.width - rotTexture.width) / 2
        rot.y = 47//533;
        rot.anchorX = rotTexture.width / 2;
        rot.anchorY = rotTexture.height / 2;
        this.addChild(rot);
        let count = 0;
        rot.addEventListener(FYGE.Event.ENTER_FRAME, () => {
            count++;
            if (count % 30 == 0) rot.rotation += 45;
        }, this)
        this.msg = new FYGE.TextField();
        this.msg.y = 125;
        this.msg.textWidth = rectBgTexture.width;
        this.msg.textAlign = FYGE.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;
    }
}

