
import Tween from "../../engine/tween/Tween";
import { Ease } from "../../engine/tween/Ease";
import { Container, Sprite } from "../../engine/2d/display";
import { TextField } from "../../engine/2d/text";
import Texture from "../../engine/2d/texture/Texture";
import { VERTICAL_ALIGN, TEXT_ALIGN } from "../../engine/2d/const";
import { layers } from "../views/layers";
import { RES } from "../RES";

let inited = false;
let _toast: Toast;
let _parent: Container
const initToast = () => {
    if (!inited) {
        inited = true;
        _toast = new Toast();
        _parent = layers.toastLayer;
        _toast.alpha = 0;
    }
}
export const showToast = (msg: string) => {
    initToast();
    _toast.show(msg)
    _parent.addChild(_toast);
    Tween.removeTweens(_toast);
    Tween.get(_toast)//动画看需求
        .set({ y: -200, alpha: 1 })
        .to({ y: 400 }, 500, Ease.quartOut)
        .wait(800)
        .to({ alpha: 0 }, 300)
        .call(() => {
            _parent.removeChild(_toast);
        })
}

/**
 * 对于之前淘宝小程序遇到的问题，需要销毁，否则会出问题
 */
export const destroyToast = () => {
    if (inited && _toast && !_toast.destroyed) {
        _toast.destroy();
        _toast = null;
        _parent = null;
    }
}

/**
 * toast类，不对外导出
 */
class Toast extends Container {
    msg: TextField;
    bg: Sprite;
    PADDING = 40;
    constructor() {
        super();
        this.mouseChildren = false;
        this.mouseEnable = false;
        var toastBgTexture: Texture = RES.getRes("toastBg.png");
        this.bg = new Sprite(toastBgTexture);
        this.bg.x = (layers.stageWidth - this.bg.width) / 2
        this.addChild(this.bg);
        this.msg = new TextField();
        this.msg.size = 28;
        this.msg.fillColor = "0xffffff";
        this.msg.text = "";
        this.msg.verticalAlign = VERTICAL_ALIGN.MIDDLE;
        this.msg.textHeight = toastBgTexture.height;
        this.msg.textAlign = TEXT_ALIGN.CENTER;
        this.addChild(this.msg)
    }
    /**
     * 显示时调用
     * @param msg 
     */
    show(msg: string) {
        this.msg.text = msg;
        //文本居中适配
        this.msg.x = (layers.stageWidth - this.msg.textWidth) / 2;
        //是否需要根据文本宽度缩放背景
        // this.bg.width = Math.min(this.msg.textWidth + this.PADDING * 2, 523);
        //背景居中适配，由于上面一行注释，那这行就构造函数里只执行一次吧
        // this.bg.x = (layers.stageWidth - this.bg.width) / 2
    }

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

}