// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // buttons: {
        //     default: [],
        //     type: [cc.Button]
        // },
        btnGroup: {
            default: null,
            type: cc.Node 
        },
        actionButton: {
            default: null,
            type: cc.Button
        },
        showImageNode: {
            default: null,
            type: cc.Node
        },
        showImageButton: {
            default: null,
            type: cc.Node
        },
        replayButton: {
            default: null,
            type: cc.Node
        },
        titleLable: {
            default: null,
            type: cc.Label
        },
        titlePlayButton: {
            default: null,
            type: cc.Node
        },

        startAudio: {
            default: null,
            type: cc.AudioClip
        },

        // buttonTapAudioEffect: {
        //     default: null,
        //     type: cc.AudioSource
        // }
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },
    setCurrentMode(val) {
        if(this.__currentMode__ === val) {
            return;
        }
        
        this.__currentMode__ = val; 
        this.lrc.setPlayInteractivateMode(val);
        // this.lrc.stopAndResetHighLight();
        // this.setPlayButtonStatus(this.BUTTON_STATUS.IDLE);
    },
    getCurrentMode() {
       return this.__currentMode__; 
    },
    getScaleValue(value) {
        // return value / base; 
        return value * this.itemScale
    },

    setNodeScale() {
        const {width: dw, height: dh} = cc.view.getDesignResolutionSize();
        const {width: fw, height: fh} = cc.view.getFrameSize();
        const gameScale = Math.min(dw / fw, dh / fh);

        let sx = fw / dw;
        let sy = fh / dh;
        const mapS = Math.min(sx, sy);
        let subNum = 720 - 640;
        
        sx = fw * gameScale / 1280;
        sy = (fh * gameScale - subNum * mapS * gameScale) / 640;
        this.node.scale = Math.min(sx, sy)
    },
    getOffsetY() {
        const {width: dw, height: dh} = cc.view.getDesignResolutionSize();
        const {width: fw, height: fh} = cc.view.getFrameSize();
        const gameScale = Math.min(dw / fw, dh / fh);
        const cw = this.node.width;
        const ch = this.node.height;
        return fh / 2 * gameScale - ch / 2 * this.node.scaleY ;
    },
    // LIFE-CYCLE CALLBACKS:
    onLoad () {
        
        this.startAudioSource = new cc.AudioSource();
        this.startAudioSource.clip = this.startAudio;
        // this.setNodeScale();


		// const ctx = rectNode.addComponent(cc.Graphics);
        // const {width: dw, height: dh} = cc.view.getDesignResolutionSize();
        // const cw = 1280;
        // const ch = 640;
        // const {width: fw, height: fh} = cc.view.getFrameSize();
        // const gameScale =  dh / fh;
        // const offsetY = fh - (fh * ch  / dh ) / gameScale
        // const offsetx = ch * gameScale ;


        this.BUTTON_STATUS = {
            ACTIVE: 'active',
            IDLE: 'idle'
        };
        // this.node.anchorX = 0.5;
        // this.node.anchorY = 0.5;
        // this.node.x = -offsetx;
        // this.node.y = -offsetY;

        this.modeNameMap = {};
        this.btnGroup.children.forEach(button => {
            this.modeNameMap[button.name] = button; 
        });
        this.lrc =this.node.getChildByName('karaoke').getComponent('karaoke')
        // this.setCurrentMode(this.lrc.PLAY_MODE.MODE1); 
        this.setPlayButtonStatus(this.BUTTON_STATUS.IDLE);

        // const {width: dw, height: dh} = cc.view.getDesignResolutionSize();
        // const {width: cw, height: ch} = cc.view.getCanvasSize();
        // const baseScale = Math.min(cw / dw, ch / dh );



        // this.setCurrentMode(this.lrc.PLAY_MODE.MODE1); 
        this.__currentMode__ = 'mode1'
        this.modeNameMap[this.getCurrentMode()].actionStatus = this.BUTTON_STATUS.ACTIVE;
        this.changeBtnActive(this.modeNameMap[this.getCurrentMode()], true);



        cc.director.on('GAME_RESOURCE_LOADED', (preloadedData) => {
            this.lrc.initialize(preloadedData);
            this.showImageNode.active = false;
            if (this.pic_url) {
                cc.assetManager.loadRemote(this.pic_url, (err, spriteFrame) => {
                    const spr = this.showImageNode.getChildByName('image').getComponent(cc.Sprite)
                    spr.spriteFrame = new cc.SpriteFrame(spriteFrame);
                    let normSF = null;
                    let pressedSF = null;
                    const b = this.showImageButton.getComponent(cc.Button);
                    normSF = b.normalSprite;
                    pressedSF = b.pressedSprite;
                    const anim = this.showImageNode.getChildByName('image').getComponent(cc.Animation);
                    let canClick = true;
                    let b4ClickIsPlaying = false;
                    anim.on(cc.Animation.EventType.FINISHED, (evt, state) => {
                        const {width,height, scale} = this.showImageNode.getChildByName('image')
                        // console.log(555, width,height, scale)

                        canClick = true;
                        if (state.name === 'popout') {
                            this.showImageNode.active = true;
                        } else {
                            this.showImageNode.active = false;
                            
                            if (b4ClickIsPlaying) {
                                this.lrc.resume();
                                b4ClickIsPlaying = false;
                            }
                            
                        }
                    })
                    this.showImageButton.on(cc.Node.EventType.TOUCH_START, (event) => {
                        this.buttonTapAudioEffect.play()  
                        if (!canClick) {
                            return;
                        }
                        this.showImageNode.active = true;
                        canClick = false;
                        const btn = event.currentTarget;
                        if (!b4ClickIsPlaying) {
                            b4ClickIsPlaying = this.lrc.isCurrentAudioSourcePlaying(); 
                        }
                        
                        
                        // const animClip = anim.getClips()[0]
                        const b = btn.getComponent(cc.Button);
                        if (b.normalSprite == normSF) {
                            // console.log(1);
                            // anim.defaultClip.wrapMode = cc.WrapMode.Normal
                            b.normalSprite = pressedSF;
                            b.hoverSprite = pressedSF;
                            anim.stop('popin');
                            anim.stop('popout');
                            anim.play('popout');
                            this.lrc.pause(); 
                            
                        } else {
                            // anim.defaultClip.wrapMode = cc.WrapMode.Reverse
                            // console.log(2);
                            b.normalSprite = normSF;
                            b.hoverSprite = normSF;
                            anim.stop('popout');
                            anim.stop('popin');
                            anim.play('popin');
                            
                        }
                    });
                });
            }
            

            // const self = this;
            this.replayButton.on(cc.Node.EventType.TOUCH_START, (event) => {
                this.buttonTapAudioEffect.play() 
                const btn = event.currentTarget;
                if (!this.lrc.isCurrentAudioSourcePlaying()) {
                    return;
                }
                this.lrc.stopAndResetHighLight();
                this.lrc.resume();
            
            });
            if (this.title_audio_url) {
                cc.assetManager.loadRemote(this.title_audio_url, (err, titleAudioCip) => {
                    this._titleAudioSource = new cc.AudioSource();
                    this._titleAudioSource.clip = titleAudioCip;
                    this._titleAudioSource.audio.on('ended', () => {
                        console.log('titleAudioCip ended');
                        this._titleAudioSource.setCurrentTime(0)
                    });
                    this._titleAudioSource.audio.on('stop', () => {
                        console.log('titleAudioCip stop');
                    });

                    this.titlePlayButton.on(cc.Node.EventType.TOUCH_START, (event) => {
                        this._titleAudioSource.stop();
                        this._titleAudioSource.setCurrentTime(0);
                        this._titleAudioSource.play();
                        // this.lrc.stopAndResetHighLight();
                    });
                });
            }
            
            
            

            // this.setCurrentMode(this.lrc.PLAY_MODE.MODE1); 
            // this.buttonGroupChange(this.modeNameMap[this.getCurrentMode()]) 
            
        });
        cc.director.on('GAME_DATA_FETCHED', function(data) {
            if (data.title) {
                this.titleLable.string = data.title;
                setTimeout(() => {
                    if (this.titleLable.node.width > this.titleLable.node.parent.width) {
                        this.titleLable.node.scale = this.titleLable.node.parent.width / this.titleLable.node.width;
                        console.log('this.titleLable.node.scale', this.titleLable.node.scale);
                    }
                }, 0);
            }



            
            // this.lrc.node.width = area.rect.width; 
            // this.lrc.node.height = area.rect.height;
            
        
            if (data.lrcData && data.lrcData.audio_url) {
                data.lrcData.audio_url = data.lrcData.audio_url.toLocaleLowerCase() 
            }
            if (data.accompany_audio_url) {
                data.accompany_audio_url = data.accompany_audio_url.toLocaleLowerCase() 
            }
            

            this.pic_url = data.pic_url;
            this.title_audio_url = data.title_audio_url
            this.lrc.prepare(data);
            // this.buttonGroupChange(this.modeNameMap[this.getCurrentMode()]) 

            // this.node.zIndex = 9999
            window.dispatchEvent(new CustomEvent('resize'), true)
            // window.dispatchEvent(new cc.Event.EventCustom('resize', true))
        }, this);
        cc.director.on('GAME_VIEW_DISPLAYED', () => {
            // this.karaoke.prepare();
        });
        window.gg =this 
        this.btnGroup.children.forEach(button => {
            console.log(button);
            button.actionStatus = this.BUTTON_STATUS.IDLE;
            button.on(cc.Node.EventType.TOUCH_START, (event) => {
                const btn = event.currentTarget;
                this.buttonGroupChange(btn) 
                // cc.log("This is a callback after the trigger event", event);
            }) 
        });
        // const btn1 = cc.find('Canvas/BodyContainer/LRCComponent/buttons-group/mode3')
        // btn1.actionStatus = this.BUTTON_STATUS.IDLE;
        // btn1.addComponent(cc.Button)
        // btn1.on('click', (event) => {
        //     const btn = event.currentTarget;
        //     this.buttonGroupChange(btn) 
        //     // cc.log("This is a callback after the trigger event", event);
        // }) ;
        // const btn2 = cc.find('Canvas/BodyContainer/LRCComponent/buttons-group/mode1')
        // btn2.actionStatus = this.BUTTON_STATUS.IDLE;
        // btn2.on(cc.Node.EventType.TOUCH_START, (event) => {
        //     const btn = event.currentTarget;
        //     this.buttonGroupChange(btn) 
        //     // cc.log("This is a callback after the trigger event", event);
        // }) ;
        
    },
    
    setPlayButtonStatus(sts){
        // this.lastButtonStateCache = this.BUTTON_STATUS.ACTIVE
        if (this.actionButton.node.buttonStatus === sts) {
            return
        }
        this.actionButton.node.children.forEach(bn => {
            bn.active = false;
        });
        this.actionButton.node.buttonStatus = sts;
        this.actionButton.node.getChildByName(sts).active = true;
        if (sts === this.BUTTON_STATUS.IDLE) {
            // this.actionButton.getComponent(cc.Animation).stop('playing');
        } else {
            // this.actionButton.getComponent(cc.Animation).play('playing');

        }
        // console.log(1, curMode, sts);
        
    },
    toggleActionButtonStatus(){
        this.buttonTapAudioEffect.play() 
        let sts = this.BUTTON_STATUS.ACTIVE;
        if(this.actionButton.node.buttonStatus == sts) {
            sts = this.BUTTON_STATUS.IDLE;
        }
        // this.setPlayButtonStatus(sts);
        // const curMode = this.getCurrentMode();
        // console.log(2, curMode, sts);
        if (sts === this.BUTTON_STATUS.ACTIVE) {
            // const sts = this.lrc.getCurrentAudioState();
            // if (sts !== cc.audioEngine.AudioState.PLAYING ) {
            //     this.lrc.play();
            // }
            if (this._titleAudioSource) {
                this._titleAudioSource.stop();
                this._titleAudioSource.setCurrentTime(0);
            }
            
            this.lrc.resume();
        } else {
            this.lrc.pause();
        }

    },

    buttonGroupChange(btn) {
        this.buttonTapAudioEffect.play() 
        console.log('btn click');
        // this.lrc.stopAndResetHighLight();
        // const dur = 0.2;
        this.btnGroup.children.forEach(button => {
            if (btn == button) {
                this.setCurrentMode(button.name)
                if (button.actionStatus == this.BUTTON_STATUS.ACTIVE) {
                    // button.node.actionStatus = this.BUTTON_STATUS.IDLE;
                    // cc.tween(button.node).to(dur, {scale: 1}).start();
                } else {
                    btn.actionStatus = this.BUTTON_STATUS.ACTIVE;
                    // cc.tween(button).to(dur, {scale: 1.2}).start()
                    this.changeBtnActive(button, true);
                }
                return;
            }
            button.actionStatus = this.BUTTON_STATUS.IDLE
            // cc.tween(button).to(dur, {scale: 1}).start()
            this.changeBtnActive(button, false);
        })
        
    },

    changeBtnActive(btn, isActive) {
        btn.getChildByName('Background').active = !isActive;
        btn.getChildByName('BackgroundActive').active = isActive;
    },
    // onButtonClick(event, index) {
    //     window.ttb = event.currentTarget;
        
    //     console.log(event, index)
    // },
    start () {
        this.buttonTapAudioEffect = this.node.getComponent(cc.AudioSource)
        this.startAudioSource.play()
    },

    update (dt) {
        if (this.lrc) {
            
            // const sts = this.lrc.getCurrentAudioState();
            const playing = this.lrc.isCurrentAudioSourcePlaying();
            let btnsts = this.BUTTON_STATUS.IDLE
            if (playing) {
                btnsts = this.BUTTON_STATUS.ACTIVE
                // this.setPlayButtonStatus(this.BUTTON_STATUS.ACTIVE); 
            } else {
                // this.setPlayButtonStatus(this.BUTTON_STATUS.IDLE); 
            }
            if (this.actionButton.node.buttonStatus === btnsts ) {
                return
            }
            this.setPlayButtonStatus(btnsts)
        }
    },
});
