// 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: {
        objMask: {
            default: null,
            type: cc.Prefab
        },
        // buttons: {
        //     default: [],
        //     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;
        //     }
        // },
    },
    getScaleValue(value) {
        // return value / base; 
        return value * this.itemScale
    },
    convertBoundingCoordinate(node, targetRect, offsetY) {
        const baseOn = node.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
        
        const min = Math.min(targetRect.width, targetRect.height);
        // const max = Math.max(targetRect.width, targetRect.height);
        // node.width = min
        // node.height = min
        // node.width = targetRect.width
        // node.height = targetRect.height
        // node.scale = (localPos2.x - localPos.x) / node.width
        // debugger
        // if(!window['nn']){
        //     window['nn'] = []
        // }
        // window['nn'].push(node);
        

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

        node.width =min 
        node.height = min
        const w = (localPos2.x - localPos.x)
        const h = (localPos2.y - localPos.y)
        const s = node.parent.height * min / 640;

        node.width = min
        node.height = min 
        // node.scale = (localPos2.x - localPos.x) / targetRect.width
        // const min = Math.min(w, h);
        if (w > h) {
            node.scale = h/ targetRect.height
        } else {
            node.scale = w / targetRect.width
        }
        // const container = node.parent; 
        // const rate =  (container.scale * container.width) / this.data.bgItem.rect.width;
		// node.scale = container.__scaleRate / container.scaleY;

        // node.width = w
        // node.height = h
        


        

        

        // 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; 
        // node.y += offsetY;
        // node.anchorX = 0.5;
        // node.anchorY = 0;
        // console.log('this.getOffsetY()', this.getOffsetY())

        
        const {x, y, width, height, scale} = node;
        console.log(4444, {x, y, width, height, scale} )
    },
    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, offsetY) {

        // const cw = 1280;
        // const ch = 640;
        // 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;

        ///////////////////////////
        const container = node.parent; 
        // const rate =  (container.scale * container.width) / this.data.bgItem.rect.width;
		const scale = container.__scaleRate / container.scaleY;
	    var width = conf.rect.width * scale;
		var height = conf.rect.height * scale;
		var x = -container.width / 2 + conf.rect.x * scale;
	    var y = container.height / 2 - conf.rect.height * scale - conf.rect.y * scale;
        ////////////////////////////

        // console.log(3333333333, {x, y, width, height});



        this.convertBoundingCoordinate(node, {
            x, y, width, height
        }, offsetY)


    },
    // LIFE-CYCLE CALLBACKS:
    onLoad () {
        
        
        // this.setNodeScale();


        this.BUTTON_STATUS = {
            ACTIVE: 'active',
            IDLE: 'idle'
        };
        this.scratchCards = this.getComponent('ScratchCards');

this.allMaskObj = [];
        cc.director.on('ADD_ANIMAT_MASK', (parentNode) => {
            console.log('ADD_ANIMAT_MASK');
            
            const objmask = cc.instantiate(this.objMask);
            // console.log(objmask); 
            objmask.zIndex = 99;
            // console.log('parentNode.scale1', parentNode.scale);
            parentNode.addChild(objmask);
            const {x, y, width, height} = parentNode;
            this.convertBoundingCoordinate(objmask, {
                x, y, width, height
            });
            objmask.x = width / 2;
            objmask.y = height / 2;
            
            const card = objmask.getComponent('ScratchCards');
            this.allMaskObj.push(card);
            objmask.off('SCRATCH_CARDFS_CLEANED')
            objmask.on('SCRATCH_CARDFS_CLEANED', () => {
                console.log('SCRATCH_CARDFS_CLEANED');
                card.fadeOutMask();
                // if (!parentNode.audioClip) {
                //     return
                // }
                // console.log(objmask._id, objmask._audioClip.url.slice(-8))
                // cc.audioEngine.stop(this.currentAudioId);
                
                
                if (!this.currentAudioId) {
                    this.allMaskObj.forEach(o => {
                        // console.log('disable', 0);
                        o.setTouchable(false)
                    })
                    parentNode.emit('click',{cb: (aid1) => {
                        const finish = (aid2) => {
                            console.log('finish', aid2)
                            this.allMaskObj.forEach(o => {
                                // console.log('enables', 0);
                                o.setTouchable(true)
                            })
                            card.node.removeFromParent();
                        }
                        cc.audioEngine.play(parentNode.audioClip, false, 1);
                        //parentNode.emit('click');
                        setTimeout(finish, parentNode.audioClip.duration * 1000)
                    }});
                    return
                    this.currentAudioId = cc.audioEngine.play(parentNode.audioClip, false, 1);
                    cc.audioEngine.setFinishCallback(this.currentAudioId, () => {
                        this.currentAudioId = cc.audioEngine.play(parentNode.audioClip, false, 1);
                        cc.audioEngine.setFinishCallback(this.currentAudioId, () => {
                            this.currentAudioId = null;
                            this.allMaskObj.forEach(o => {
                                o.setTouchable(true)
                            })
                            card.node.removeFromParent();
                            // parentNode.emit('click');
                        });
                        this.currentAudioId = null;
                    });
                } 
                
            });
            card.initRectMaskPoints()

        });
        cc.director.on('GAME_RESOURCE_LOADED', (parentNode) => {
            console.log('GAME_RESOURCE_LOADED')
            return; 
             // from data find text area config 
             const maskRects = this.configData.hotZoneItemArr.filter(item => {
                return +item.gIdx === 2;
            }).map( r => {return {...r}});
            
            this.allMaskObj = [];
            if (maskRects && maskRects.length) {
                for (let r of maskRects) {
                    const rect = {...r}
                    const objmask = cc.instantiate(this.objMask);
                    // console.log(objmask); 
                    objmask.zIndex = 99;
                    // console.log('parentNode.scale1', parentNode.scale);
                    parentNode.addChild(objmask);
                    this.setToRectArea(objmask, rect, parentNode.y);
                    
                    const wrap = (mNode) => {
                        if (rect.audio_url) {
                            
                            cc.assetManager.loadRemote(rect.audio_url, null, (err, audioClip) => {
                                if(err) {
                                    // TODO handle error
                                    return;
                                }
                                // console.log(mNode._id, rect.audio_url.slice(-8))
                                mNode._audioClip = audioClip;
                            });
                        }
                    }
                    wrap(objmask); 
                    const card = objmask.getComponent('ScratchCards');
                    this.allMaskObj.push(card);
                    objmask.off('SCRATCH_CARDFS_CLEANED')
                    objmask.on('SCRATCH_CARDFS_CLEANED', () => {
                        card.fadeOutMask();
                        if (!objmask._audioClip) {
                            return
                        }
                        // console.log(objmask._id, objmask._audioClip.url.slice(-8))
                        cc.audioEngine.stop(this.currentAudioId);
                        
                        this.allMaskObj.forEach(o => {
                            o.setTouchable(false)
                        })
                        if (!this.currentAudioId) {
                            this.currentAudioId = cc.audioEngine.play(objmask._audioClip, false, 1);
                            cc.audioEngine.setFinishCallback(this.currentAudioId, () => {
                                this.currentAudioId = cc.audioEngine.play(objmask._audioClip, false, 1);
                                cc.audioEngine.setFinishCallback(this.currentAudioId, () => {
                                    this.currentAudioId = null;
                                    this.allMaskObj.forEach(o => {
                                        o.setTouchable(true)
                                    })
                                });
                                this.currentAudioId = null;
                            });
                        } 
                        
                    });
                    card.initRectMaskPoints()
                }
            }
            window.dispatchEvent(new CustomEvent('resize'), true)
            console.log('parentNode.scale1.5s', parentNode.scale);
        });
        cc.director.on('GAME_DATA_FETCHED', (data) => {
            console.log('GAME_DATA_FETCHED');
            this.configData = data;
            // return
            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;



            





            



            
            // this.lrc.node.width = area.rect.width; 
            // this.lrc.node.height = area.rect.height;
            
        

            
            // this.node.y = this.getOffsetY();


            // this.lrc.prepare(data);

            this.node.zIndex = 9999
            
        });
        cc.director.on('GAME_VIEW_DISPLAYED', () => {
            // this.karaoke.prepare();
            console.log('GAME_VIEW_DISPLAYED')
        });
        window.gg =this 
        
    },
    


    // onButtonClick(event, index) {
    //     window.ttb = event.currentTarget;
        
    //     console.log(event, index)
    // },
    start () {
        

    },

    update (dt) {
        
    },
});
