// 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;
        //     }
        // },
    },
    setData(data, scale){
            
        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 = 1 //this.rootNodeScale;


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







        // from data find text area config 
        // const lrcRect = {rect: {x: -10, y: -10,  width: 400, height: 200}}

        // const tmpNode = new cc.Node();
        // const g = tmpNode.addComponent(cc.Graphics);
        // g.fillColor = cc.Color.RED;
        // g.fillRect(0, 0, 200, 200);
        // tmpNode.parent = this.lrc.node;

        // console.log('aaaaa', this.lrc.calcHighlightRichText.node.getContentSize());

        
        // scale = 1;
        this.lrc.node.x = 100 
        this.lrc.node.y = 0
        this.lrc.node.width = 370 
        this.lrc.node.height = 200 
        // this.lrc.node.scale = scale;
        this.lrc.prepare(data);


        const textArea = this.lrc.calcHighlightRichText.node.getContentSize()
        this.lrc.node.height = textArea.height + 10;

        // this.setToRectArea(this.lrc.node, lrcRect, true);
        console.log(1,data);
        console.log('this.lrc.node: ', this.lrc.node);

        this.__currentMode__ = this.lrc.PLAY_MODE.MODE1; 
        this.lrc.setPlayInteractivateMode(this.lrc.PLAY_MODE.MODE1);
        this.lrc.initialize();


        window.dispatchEvent(new CustomEvent('resize'), true)

        console.log('aaa~~~~', this.lrc.node);
   },

   isPlaying() {
    return this.lrc.isCurrentAudioSourcePlaying()
   },
   playSong() {
       console.log(' in playSong')
       if (!this.lrc.isCurrentAudioSourcePlaying()) {
        this.lrc.resume();
       }
    
   },
//    pauseSong() {
//     console.log(' in pauseSong')
//     this.lrc.pause();
//    },

   stopSong() {
    this.lrc.stopAndResetHighLight();
   },
    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 = 720;
        // 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')
        // 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_VIEW_DISPLAYED', () => {
        //     // this.karaoke.prepare();
        // });
        // window.gg =this 
        // this.btnGroup.children.forEach(button => {
        //     button.actionStatus = this.BUTTON_STATUS.IDLE;
        //     button.on(cc.Node.EventType.TOUCH_START, (event) => {
        //         const btn = event.currentTarget;
        //         window.bb = btn;
        //         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(){
        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) {
        return
        // 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 () {
        

    },

    // 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
    //         }
    //     }
    // },
});
