import {
    ShapeRect,
    MySprite,
    tweenChange
} from './Unit';

import{
    playAudio
} from './AudioUtil';

export class Buttion {
    bg;

    up;

    down;

    scaleX = 1;

    scaleY = 1;

    images = new Map();

    audio;

    curStatus;

    constructor(images) {
        this.images = images;
    }

    setScaleXY(scale) {
        this.scaleX = this.scaleY = scale;
    }

    init(upImgKey, downImgKey) {
        const bg = new ShapeRect();
        bg.alpha = 0;
        this.bg = bg;

        const up = new MySprite();
        up.init(this.images.get(upImgKey));
        up.scaleX = this.scaleX;
        up.scaleY = this.scaleY;
        up.x = up.getBoundingBox().width / 2;
        up.y = up.getBoundingBox().height / 2;
        this.up = up;
        bg.addChild(up);
        this.curStatus = up;

        const down = new MySprite();
        down.init(this.images.get(downImgKey));
        down.scaleX = this.scaleX;
        down.scaleY = this.scaleY;
        down.alpha = 0;
        down.x = up.x;
        down.y = up.y;
        this.down = down;
        bg.addChild(down);

        bg.setSize(up.getBoundingBox().width, up.getBoundingBox().height);
    }

    click(callback = null) {
        
        playAudio(this.audio, true, callback);

        this.up.alpha = 0;

        this.down.alpha = 1;

        this.curStatus = this.down;

        setTimeout(() => {
            this.resetStatus();
        }, 100);
    }

    resetStatus(){
        this.up.alpha = 1;
        this.down.alpha = 0;
        this.curStatus = this.up;
    }

    hide(time = 0.3, callback = null){

        tweenChange(this.curStatus, { alpha: 0 }, time, ()=>{
            if(callback){
                callback();
            }
        });
    }
}