import { MConfigs } from "../Global/MConfigs";

export default class GuideMask extends egret.DisplayObjectContainer {
    private tweenList: egret.DisplayObject[] = [];
    constructor(index: number, x: number, y: number) {
        super();
        const config = MConfigs.guide[index];


        let bg = new egret.Shape();
        bg.graphics.beginFill(0x000000);
        bg.graphics.drawRect(0, 0, 750, 1624);
        bg.graphics.endFill();
        bg.alpha = 0.7;

        let texture = RES.getRes(config.mask);
        let bitmap = new egret.Bitmap(texture);
        bitmap.x = x - texture.textureWidth / 2;
        bitmap.y = y - texture.textureHeight / 2;

        let container: egret.DisplayObjectContainer = new egret.DisplayObjectContainer();

        container.addChild(bg);
        container.addChild(bitmap);
        bitmap.blendMode = egret.BlendMode.ERASE;

        let renderTexture: egret.RenderTexture = new egret.RenderTexture();
        renderTexture.drawToTexture(container);
        let blendBitmap = new egret.Bitmap(renderTexture);
        this.addChild(blendBitmap);

        let offsetToMask = config.text.offsetToMask;
        let label = new eui.Label(config.text.str);
        label.size = 24;
        label.x = offsetToMask.x + bitmap.x;
        label.y = offsetToMask.y + bitmap.y;
        this.textBlink(label);
        this.addChild(label);
        this.tweenList.push(label);

        label.validateSize();
        if (label.x < 0) {
            label.x = 0;
        } else if (label.x + label.width > 750) {
            label.x = 750 - label.width;
        }

        if (config.arrow) {
            let leftArrow = new eui.Image("guide_arrow_png");
            leftArrow.x = 157, leftArrow.y = 908;
            this.arrowTween(leftArrow, -1, 157);
            this.addChild(leftArrow);
            this.tweenList.push(leftArrow);

            let rightArrow = new eui.Image("guide_arrow_png");
            rightArrow.scaleX = -1;
            rightArrow.x = 590, rightArrow.y = 908;
            this.arrowTween(rightArrow, 1, 590);
            this.addChild(rightArrow);
            this.tweenList.push(rightArrow);
        }


        this.touchEnabled = true;
        this.onTap(this, () => {
            this.onClick && this.onClick();
        });
    }

    private textBlink(label: eui.Label) {
        egret.Tween.get(label).to({ alpha: 0 }, 400).to({ alpha: 1 }, 200).call(() => { this.textBlink(label) });
    }

    private arrowTween(arrow: eui.Image, dir: 1 | -1, startPos: number) {
        egret.Tween.get(arrow).to({ x: startPos + dir * 100 }, 700).set({ x: startPos }).call(() => { this.arrowTween(arrow, dir, startPos) });
    }

    onClick: () => void;

    destroy() {
        this.tweenList.forEach(e => {
            egret.Tween.removeTweens(e);
        })
        super.destroy();
    }
}