// 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
        },
        // 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
    },
    convertBoundingCoordinate(node, targetRect, resize) {
        const baseOn = node.parent; // targetRect.parent ? targetRect.parent : this.node;//cc.find('Canvas');//targetRect.parent;// cc.find('Canvas');
        const worldPos = baseOn.convertToWorldSpaceAR(cc.v2(targetRect.x, targetRect.y));
        const localPos = node._parent.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));

        const worldPos2 = baseOn.convertToWorldSpaceAR(cc.v2(targetRect.x + targetRect.width, targetRect.y + targetRect.height));
        const localPos2 = node._parent.convertToNodeSpaceAR(cc.v2(worldPos2.x, worldPos2.y));

        // this.actionButton.node.x = localPos.x; 
        // localPos.x + targetNode.width
        if (resize) {
            node.width = targetRect.width
            node.height = targetRect.height
            node.scale = (localPos2.x - localPos.x) / node.width
        }



        // node.width = (localPos2.x - localPos.x)
        // node.height = (localPos2.y - localPos.y)


        node.y = (localPos2.y + localPos.y) / 2;
        node.x = (localPos2.x + localPos.x) / 2;
        const { x, y, width, height } = node;
        console.log(2, { x, y, width, height })
    },
    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;
    },
    setToRectArea(node, conf, resize) {




        // 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;
        // console.log(3333, conf.rect)
        let width = this.getScaleValue(conf.rect.width)
        let height = this.getScaleValue(conf.rect.height)
        let x = this.getScaleValue(conf.rect.x)
            // + conf.rect.width - conf.rect.width * node.anchorX
            - cw / 2;
        let y = this.getScaleValue(-conf.rect.y)
            // - conf.rect.height * node.anchorY
            + this.getScaleValue(-conf.rect.height)
            + ch / 2;

        // let x = this.getScaleValue(conf.rect.x, conf.mapScale) 
        // + conf.rect.width - conf.rect.width //* node.anchorX
        // - dw / 2;
        // let y = this.getScaleValue(-conf.rect.y, conf.mapScale) 
        // - conf.rect.height// * node.anchorY
        // + dh / 2;
        // console.log(4444,{
        //     x, y, width, height
        // });

        // const rectNode = new cc.Node();
        // rectNode.anchorX = 0;
        // rectNode.anchorY = 0;
        // this.node.addChild(rectNode);
        // const ctx = rectNode.addComponent(cc.Graphics);
        // // 红色矩形
        // ctx.lineWidth = 4;
        // ctx.strokeColor = cc.Color.RED;
        // ctx.fillColor = cc.Color.WHITE.setA(100);        
        // ctx.rect(0, 0, rectNode.width, rectNode.height);
        // ctx.stroke();
        // ctx.fill()
        // rectNode.width = width
        // rectNode.height = height
        // rectNode.x = x
        // rectNode.y = y;

        this.convertBoundingCoordinate(node, {
            x, y, width, height
        }, resize)
        // x *= gameScale ;
        // y *= gameScale ;

        // y+= (ch * gameScale / 2 )
        // // width/height = width * gameScale  / sh
        // // width * sh = width * gameScale * height 
        // width *= gameScale ;
        // height *= gameScale ;



        // bh * actionArea.width / bw
        // if (x > 0) {
        //     x -= width;
        // }
        // if (x < 0) {
        //     x += width / 2;
        // }

        // if (y > 0) {
        //     y -= height
        // }
        // console.log(x,y, width,height);
        // return {x, y, width, height}
    },
    // LIFE-CYCLE CALLBACKS:
    onLoad() {


        // 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 ;

        window.play = this;
        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;
        // console.log(123123);

        this.modeNameMap = {};
        this.btnGroup.children.forEach(button => {
            this.modeNameMap[button.name] = button;
        });
        this.lrc = this.node.getChildByName('karaoke').getComponent('karaoke_WDL_Demo_02')
        // 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 );



        cc.director.on('GAME_RESOURCE_LOADED_sb_karaoke_cocos', () => {
            this.lrc.initialize();
            this.setCurrentMode(this.lrc.PLAY_MODE.MODE1);
            this.buttonGroupChange(this.modeNameMap[this.getCurrentMode()])
            // this.lrc.node.zIndex = 99999
        });
        cc.director.on('GAME_DATA_FETCHED_sb_karaoke_cocos', (data) => {

            const { width: dw, height: dh } = cc.view.getDesignResolutionSize();
            const { width: fw, height: fh } = cc.view.getFrameSize();
            this._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 * this._gameScale / 1280;
            sy = (fh * this._gameScale - subNum * mapS * this._gameScale) / 640;
            this.rootNodeScale = Math.min(sx, sy);
            this.node.scale = this.rootNodeScale;


            const rate = (this.rootNodeScale * 1280) / data.bgItem.rect.width;
            this.itemScale = rate / this.rootNodeScale;







            // from data find text area config 
            const lrcRect = data.hotZoneItemArr.find(item => {
                return +item.gIdx === 2;
            });
            const modeGroupRect = data.hotZoneItemArr.find(item => {
                return +item.gIdx === 4;
            });

            const actionbBtnRect = data.hotZoneItemArr.find(item => {
                return +item.gIdx === 3;
            });



            if (lrcRect) {
                this.setToRectArea(this.lrc.node, lrcRect, true);
                // this.lrc.node.x = lrcArea.x;
                // this.lrc.node.y = lrcArea.y;
                // this.lrc.node.width = lrcArea.width; 
                // this.lrc.node.height = lrcArea.height;
                // this.lrc.node.anchorX = 0;
                // this.lrc.node.anchorY = 1;

                if (this.lrc.node) {
                    this.lrc.node.zIndex = 99999;
                } else {
                    console.log("!this.lrc.node")
                }
            } else {

                this.lrc.node.active = false;
            }
            if (modeGroupRect) {
                this.setToRectArea(this.btnGroup, modeGroupRect);
                // this.btnGroup.x = modeArea.x;
                // this.btnGroup.y = modeArea.y;
                // this.btnGroup.width = modeArea.width; 
                // this.btnGroup.height = modeArea.height;
                // this.btnGroup.anchorX = 0;
                // this.btnGroup.anchorY = 1;
                this.btnGroup.children.forEach(b => {
                    b.getComponent(cc.Widget).enable = false;
                    b.getComponent(cc.Widget).enable = true;
                })

                if (this.btnGroup) {
                    this.btnGroup.zIndex = 99999;

                } else {
                    console.log("!this.btnGroup");
                }

            } else {
                this.btnGroup.active = false;
            }
            if (actionbBtnRect) {
                this.setToRectArea(this.actionButton.node, actionbBtnRect);
                // this.actionButton.node.x = actionArea.x;
                // this.actionButton.node.y = actionArea.y;
                // this.actionButton.node.anchorX = 0;
                // this.actionButton.node.anchorY = 1;
                // const { width: bw, height: bh } = this.actionButton.node;  
                // this.actionButton.node.width = actionArea.width; 
                // this.actionButton.node.height = bh * actionArea.width / bw ; //actionArea.height;

                if (this.actionButton.node) {
                    this.actionButton.node.zIndex = 99999;

                } else {
                    console.log("!this.actionButton.node")
                }
            } else {
                this.actionButton.node.active = false;
            }





            // 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.node.y = this.getOffsetY();


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

            if (this.node) {
                this.node.zIndex = 9999

            } else {
                console.log('!this.node');
            }
            // window.dispatchEvent(new CustomEvent('resize'), true)
            // window.dispatchEvent(new cc.Event.EventCustom('resize', true))
        }, this);
        cc.director.on('GAME_VIEW_DISPLAYED', function () {
            // this.karaoke.prepare();
        }, this);
        window.gg = this
        this.btnGroup.children.forEach(button => {
            button.actionStatus = this.BUTTON_STATUS.IDLE;
            button.on(cc.Node.EventType.TOUCH_START, function (event) {
                const btn = event.currentTarget;
                window.bb = btn;
                this.buttonGroupChange(btn)
                // cc.log("This is a callback after the trigger event", event);
            }, this)
        });
        ;
    },

    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() {
        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();
            // }
            this.lrc.resume();
        } else {
            this.lrc.pause();
        }

    },

    buttonGroupChange(btn) {
        // 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() {

    },

    onDestroy() {
        cc.director.off('GAME_RESOURCE_LOADED_sb_karaoke_cocos');
        cc.director.off('GAME_DATA_FETCHED_sb_karaoke_cocos');
        cc.director.off('GAME_VIEW_DISPLAYED');
    },

    update(dt) {
        if (this.lrc) {
            // const sts = this.lrc.getCurrentAudioState();
            const sts = this.lrc.isCurrentAudioSourcePlaying();
            if (sts /*sts === cc.audioEngine.AudioState.PLAYING*/) {
                this.setPlayButtonStatus(this.BUTTON_STATUS.ACTIVE);
                // this.lastButtonStateCache = this.BUTTON_STATUS.ACTIVE
            } else {
                this.setPlayButtonStatus(this.BUTTON_STATUS.IDLE);
                // this.lastButtonStateCache = this.BUTTON_STATUS.IDLE
            }
        }
    },
});
