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

import {
    pauseAudio,
    playAudio
} from './AudioUtil'

export class Handclap {

    bg: ShapeRect;

    leftHand: MySprite;

    rightHand: MySprite;

    audio;

    playing = false;


    init(leftHandImgObj, rightHandImgObj, scaleX: number, sacleY: number) {

        const leftHand = new MySprite();
        leftHand.init(leftHandImgObj);
        leftHand.scaleX = scaleX;
        leftHand.scaleY = sacleY;
        this.leftHand = leftHand;

        const rightHand = new MySprite();
        rightHand.init(rightHandImgObj);
        rightHand.scaleX = scaleX;
        rightHand.scaleY = sacleY;
        this.rightHand = rightHand;

        let height = Math.max(rightHand.getBoundingBox().height, leftHand.getBoundingBox().height);

        let width = leftHand.getBoundingBox().width + rightHand.getBoundingBox().width;

        const bg = new ShapeRect();
        bg.setSize(width, height);
        bg.alpha = 0;
        this.bg = bg;      

        rightHand.x = leftHand.getBoundingBox().width + rightHand.getBoundingBox().width / 2;
        rightHand.y = height/2;
        bg.addChild(rightHand);

        leftHand.x = leftHand.getBoundingBox().width/ 2;
        leftHand.y = height/2;
        bg.addChild(leftHand);
    }

    getWidth(){
        return this.bg.getBoundingBox().width;
    }

    getHight(){
        return this.bg.getBoundingBox().height;
    }

    play(callback = null){
        
        //播放音效
        playAudio(this.audio, false, ()=>{
            this.playing = false;

            if(callback){
                callback();
            }
        });

        const applaud = () => {

            if(this.playing){

                let scaleX = this.leftHand.scaleX;

                let leftHandX = this.leftHand.x;

                tweenChange(this.leftHand, {x: leftHandX + 60 * scaleX}, 0.1, () => {

                    tweenChange(this.leftHand, {x: leftHandX}, 0.1, ()=>{

                        setTimeout(() => {
                            applaud();
                        }, 50);
                       

                    });
                });

                let rightHandX = this.rightHand.x;

                tweenChange(this.rightHand, {x: rightHandX - 60 * scaleX}, 0.1, () => {

                    tweenChange(this.rightHand, {x: rightHandX}, 0.1, ()=>{

                    });
                });
            }
        }

        this.playing = true;

        //鼓掌
        applaud();
    }

    /**
     * 停止鼓掌
     * @param callback 
     */
    stop(callback = null){

        this.playing = false;

        pauseAudio(this.audio, true);

        if(callback){
            callback();
        }
    }
}