/*
 * MusicBtn.ts
 * Created by 还有醋v on 2021/4/27.
 * Copyright © 2021 haiyoucuv. All rights reserved.
 */


import Button = FYGE.Button;
import Container = FYGE.Container;
import Texture = FYGE.Texture;
import MouseEvent = FYGE.MouseEvent;
import { sendTbNet, TbNetName } from "../TaoBaoNet";

export default class MusicBtn extends Container {

    private static status = true;

    private static btns: MusicBtn[] = [];

    // 为了解决按钮改变图片会重设锚点的问题
    // 解决方案：
    //    1.记录MusicBtn设置的anchor
    //    2.重写 anchorX anchorY anchor.set
    //    3.在修改按钮图片的时候 设置按钮 anchor 为记录的 anchor
    btnAnchor: number[] = [0, 0];

    set anchorX(value: number) {
        this.btn.anchorX = value;
        this.btnAnchor[0] = value;
    }

    set anchorY(value: number) {
        this.btn.anchorY = value;
        this.btnAnchor[1] = value;
    }

    public static changeMusicStatus(status: boolean) {
        MusicBtn.status = status;

        MusicBtn.btns.forEach((v) => {
            v.btn.changeTexture(status ? v.on : v.off);
            v.btn.anchor.set(v.btnAnchor[0], v.btnAnchor[1]);   // 在修改按钮图片的时候 设置按钮 anchor 为记录的 anchor
        });

        sendTbNet(TbNetName.openMusic, { isOn: status });

    }

    private btn: Button;

    constructor(private on: Texture, private off: Texture) {
        super();

        this.btn = this.addChild(new Button(MusicBtn.status ? this.on : this.off));

        this.btn.addEventListener(MouseEvent.CLICK, MusicBtn.onClick, this);

        MusicBtn.btns.push(this);

        // 重写 anchor.set
        this.anchor.set = (x, y) => {
            this.btn.anchor.set(x, y);
            this.btnAnchor[0] = x;
            this.btnAnchor[1] = y;
        }

    }

    private static onClick() {
        MusicBtn.changeMusicStatus(!MusicBtn.status);
    }

    destroy() {
        super.destroy();

        MusicBtn.btns.splice(MusicBtn.btns.indexOf(this), 1);

        this.btn.removeEventListener(MouseEvent.CLICK, MusicBtn.onClick, this);
    }
}
