import Cartoon from "./Cartoon"
import defaultData from "./defaultData"
import { jelly } from "./utils"

export default class GameLogic {
  g_cartoon = null;
  g_formData = null
  g_enableClick = true;
  g_canvas = null;
  g_systemOption = null;
  g_useDefaultData = false;
  g_curDragonDisplay = null;
  
  m_questionAudioPlayed = false;
  m_currentQuestion = -1;
  m_questionDone = false;
  constructor(formData, systemOption) {
    this.g_systemOption = systemOption;
    this.g_canvas = cc.find('Canvas');
    this.g_cartoon = new Cartoon(cc);

    if(!formData.contentObj.dataArray || formData.contentObj.dataArray.length == 0) {
      this.g_useDefaultData = true;
      this.g_formData = defaultData
      console.warn("User default data =>", this.g_formData)
    } else {
      this.g_formData = formData.contentObj;
      console.log("User saved data =>", this.g_formData)
    }
    this.m_currentQuestion = 0;
    this.g_cartoon.initLocalAudios([
    	"test_audio"
    ])
    this.initNodes();
    this.initImageCards();
    this.initTitle();
    // this.initQuestionPannel();
    // this.initButtons();
    // this.initMaskLayer();
    // this.initDragonBonesContainer();
    // this.checkButtonStatus()

    // // Load quesiton
    // this.initSelectedCards();
    // this.initText();
    // this.initCenterImage();

    // this.g_enableClick = false;
    // this.resetAllSelectedCards();
    // this.playQuestion(()=>{
    //   this.g_enableClick = true;
    // })
  }

  initNodes() {
  	this.g_cartoon.initCartoonElement("title_text", this.g_cartoon.getNodeByPath(`Canvas/title/text`))
    for(let index=0; index<10; index++) {
      this.g_cartoon.initCartoonElement(`card_${index+1}`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}`))
      this.g_cartoon.initCartoonElement(`card_${index+1}_normal`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/normal`));
      this.g_cartoon.initCartoonElement(`card_${index+1}_selected`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/selected`));
      this.g_cartoon.initCartoonElement(`card_${index+1}_bell`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/bell`))
      this.g_cartoon.initCartoonElement(`card_${index+1}_bell_text`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/bell/index`))
      this.g_cartoon.initCartoonElement(`card_${index+1}_bell_outline`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/bell/bell_outline`));
      this.g_cartoon.initCartoonElement(`card_${index+1}_image_container`, this.g_cartoon.getNodeByPath(`Canvas/card_${index+1}/container/image`));
    }
    // this.resetPosition()
  }

  resetPosition() {
    console.log(this.g_cartoon.getCartoonElement("question_title_pannel"))
    // this.g_cartoon.getCartoonElement("bottomPart_pannel").setLocation(this.g_systemOption.frameSize.width * this.g_systemOption.cocosScale, 4)
    // this.g_cartoon.getCartoonElement("question_title_pannel").setLocation(this.g_systemOption.frameSize.width * this.g_systemOption.cocosScale / 2)
    // this.g_cartoon.getCartoonElement(`selected_1`).setLocation(0)
    // this.g_cartoon.getCartoonElement(`selected_2`).setLocation(0)
    // this.g_cartoon.getCartoonElement(`selected_3`).setLocation(0)
    // this.g_cartoon.getCartoonElement(`selected_4`).setLocation(0)
    // this.g_cartoon.getCartoonElement(`selected_5`).setLocation(cc.winSize.width - 150)
    // this.g_cartoon.getCartoonElement(`selected_6`).setLocation(cc.winSize.width - 100)
    // this.g_cartoon.getCartoonElement(`selected_7`).setLocation(cc.winSize.width - 80)
    // this.g_cartoon.getCartoonElement(`selected_8`).setLocation(cc.winSize.width - 160)
    // this.g_cartoon.getNodeByPath(`Canvas/center_image`).x = cc.winSize.width / 2 + 20
    // this.g_cartoon.getNodeByPath(`Canvas/center_image`).y = cc.winSize.height / 2
  }

  initImageCards() {
  	for (let index = 0; index < 10; index++) {
      let dataItem = this.g_formData.dataArray[index];
      let card = this.g_cartoon.getCartoonElement(`card_${index+1}`)
      let cardNormal = this.g_cartoon.getCartoonElement(`card_${index+1}_normal`)
      let cardSelected = this.g_cartoon.getCartoonElement(`card_${index+1}_selected`)
      let imageContainer = this.g_cartoon.getCartoonElement(`card_${index+1}_image_container`)
      let bellOutline = this.g_cartoon.getCartoonElement(`card_${index+1}_bell_outline`)
      let bellText = this.g_cartoon.getCartoonElement(`card_${index+1}_bell_text`)
      
      bellText.node.getComponent(cc.Label).font = this.g_cartoon.getFontFamily("Comic Sans MS")
    	bellText.node.getComponent(cc.Label).fontSize = 20

      if(this.g_useDefaultData || !dataItem) {
        let fr = this.getSpriteFrimeByResName("card_demo")
        imageContainer.node.setScale(1)
        imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
      } else {
        this.getSpriteFrimeByUrl(dataItem.image_url, (fr)=>{
          let sx = 220 / fr.getRect().width;
          let sy = 110 / fr.getRect().height;
          let s = Math.min(sx, sy)
          imageContainer.node.width = s * fr.getRect().width;
          imageContainer.node.height = s * fr.getRect().height;
          imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
        })
      }


      bellOutline.node.setScale(0);

      this.g_cartoon.subscribeTouchEvent(`card_${index+1}_image_container`, ()=>{
      	for(let i=0; i<10; i++) {
      		if(i!=index) {
      			this.g_cartoon.getCartoonElement(`card_${i+1}_normal`).node.opacity = 255;
		      	this.g_cartoon.getCartoonElement(`card_${i+1}_selected`).node.opacity = 0;
			    } else {
			    	this.g_cartoon.getCartoonElement(`card_${i+1}_normal`).node.opacity = 0;
			      this.g_cartoon.getCartoonElement(`card_${i+1}_selected`).node.opacity = 255;
			    }
		    }
      })

      card.tweenHandle = null;
      const runBell = () => {
      	bellOutline.node.setScale(1, 1)
      	bellOutline.node.opacity = 255;
      	card.tweenHandle = this.g_cartoon.tweenChange(bellOutline.node, {scaleX: 2, scaleY: 2, opacity: 0}, 0.4, ()=>{
      		runBell()
      	})
      }

      const stopBell = () => {
      	if(card.tweenHandle) {
      		card.tweenHandle.stop();
      		card.tweenHandle = null
      	}
      	bellOutline.node.setScale(0, 0)
      	bellOutline.node.opacity = 0;
      }

      this.g_cartoon.subscribeTouchEvent(`card_${index+1}_bell`, ()=>{
      	this.g_cartoon.stopAllAudio()
      	this.g_cartoon.playAudio("test_audio", ()=>{
      		stopBell()
      	})
      	runBell()
      })
    }
  }

  initCenterImage() {
    let imageContainer = this.g_cartoon.getCartoonElement("center_image_container")
    if(!this.g_formData.dataArray[this.m_currentQuestion].question.centerImage_url) {
      let fr = this.getSpriteFrimeByResName("default_stage")
      imageContainer.node.setScale(1)
      imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
    } else {
      let parentWidth = imageContainer.node.parent.width
      let parentHeight = imageContainer.node.parent.height
      this.getSpriteFrimeByUrl(this.g_formData.dataArray[this.m_currentQuestion].question.centerImage_url, (fr)=>{
        imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
        imageContainer.node.scaleX = parentWidth / imageContainer.node.width
        imageContainer.node.scaleY = parentHeight / imageContainer.node.height
      })
    } 
  }

  initTitle() {
		this.g_cartoon.getCartoonElement("title_text").node.getComponent(cc.Label).string = "It's My Day"
		this.g_cartoon.getCartoonElement("title_text").node.getComponent(cc.Label).font = this.g_cartoon.getFontFamily("Comic Sans MS")
    this.g_cartoon.getCartoonElement("title_text").node.getComponent(cc.Label).fontSize = 32
  }

  initQuestionPannel() {
    let title = this.g_cartoon.getCartoonElement("question_title_pannel")
    let body = this.g_cartoon.getCartoonElement("question_body_pannel")
    let bodyText = this.g_cartoon.getCartoonElement("question_body_pannel_text")

    // title.node.y = cc.winSize.height - this.g_cartoon.getCartoonElement("question_title_pannel_background").node.height / 2
    this.g_cartoon.subscribeTouchEvent(title.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      if(this.g_formData.dataArray[this.m_currentQuestion].question.question_audio_url) {
        this.g_cartoon.stopAllAudio()
        this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.question_audio_url, ()=>{

        })
      }
    })

    body.in = (callback) => {
      body.node.y = -cc.winSize.height / 2 - this.g_cartoon.getCartoonElement("question_body_pannel_background").node.height / 2
      this.g_cartoon.tweenChange(body.node, {y: -270}, 0.5, ()=>{
        this.g_cartoon.tweenChange(bodyText.node, {opacity: 255}, 0.5, ()=>{
          if(callback) {
            callback()
          }
        })
      })
    }

    body.out = () => {
      bodyText.node.opacity = 0;
      body.node.y = -cc.winSize.height / 2 - this.g_cartoon.getCartoonElement("question_body_pannel_background").node.height / 2
    }

    this.g_cartoon.subscribeTouchEvent(body.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      
      if(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url) {
        this.g_cartoon.stopAllAudio()
        this.g_cartoon.getCartoonElement("Text_DragonBones").dragonBones.showDragonBones(1)
        this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url, ()=>{

        })
      }
    })
  }

  initDragonBonesContainer () {
    let container =  this.g_cartoon.getCartoonElement("DragonBones-Container")

    container.hide = () => {
      // container.node.scaleX = 0
      // container.node.scaleY = 0
      container.node.opacity = 0;
    }

    container.show = (callback) => {
      // container.node.y = container.node.y + 220;
      container.node.opacity = 0;
      this.g_cartoon.tweenChange(container.node, {opacity: 255}, 0.7, ()=>{
        if(callback) {
          callback()
        }
      })
    }
  }

  initSelectedCards() {
    let order = [2,6,3,7,1,5,4,8]
    let dragonBones = this.g_formData.dataArray[this.m_currentQuestion].dragonBones;
    for (let index = 0; index < 8; index++) {
      let dataItem = this.g_formData.dataArray[this.m_currentQuestion].selectCards[index];
      let el = this.g_cartoon.getCartoonElement(`selected_${order[index]}`)
      if(!dataItem) {
        el.node.active = false;
        continue;
      } else {
        el.node.active = true;
      }
    
      this.g_cartoon.getCartoonElement(`selected_${order[index]}_highlight`).node.active = false;
      this.g_cartoon.getCartoonElement(`selected_${order[index]}_play`).node.active = false;

      let audioEl = this.g_cartoon.getCartoonElement(`selected_${order[index]}_speaker`);
      let audioAni = this.g_cartoon.creatSpeaker(audioEl.node, "icon_sound", "icon_sound_2")
      let imageContainer = this.g_cartoon.getCartoonElement(`selected_${order[index]}_image_container`)
      let errorIcon = this.g_cartoon.getCartoonElement(`selected_${order[index]}_error_x`)
      errorIcon.node.scale = 0;
      let errorMask = this.g_cartoon.getCartoonElement(`selected_${order[index]}_error_mask`)
      errorMask.node.active = false;

      if(this.g_useDefaultData) {
        let fr = this.getSpriteFrimeByResName(dataItem.image_url)
        imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
      } else {
        this.getSpriteFrimeByUrl(dataItem.image_url, (fr)=>{
          imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
        })
      }
      
      this.g_cartoon.subscribeTouchEvent(el.key, ()=>{
        if(!this.g_enableClick) {
          console.warn("g_enableClick disabeld!")
          return;
        }
        if(this.m_questionDone) {
          return;
        }
        this.g_enableClick = false;
        if(dataItem.isAnswer) {
          this.maskOthers(order[index]-1)
          this.g_cartoon.getCartoonElement(`selected_${order[index]}_highlight`).node.active = true;
          this.g_cartoon.playAudio("right_goodjob")
          this.showRightCircle(imageContainer, ()=>{
            this.m_questionDone = true;
            this.g_enableClick = true;
            if(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url) {
              this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url, ()=>{
                this.g_cartoon.playAudio("good_job")
              })
            } else {
              this.g_cartoon.playAudio("good_job")
            }
            if(dragonBones && dragonBones.texPngData.url && dragonBones.skeJsonData.url && dragonBones.texJsonData.url) {
              this.g_cartoon.getCartoonElement("Center_DragonBones").dragonBones.setDragonBones(dragonBones, (handle)=>{
                this.g_cartoon.getCartoonElement("DragonBones-Container").show(()=>{
                  handle.showDragonBones(0);
                }, ()=>{
                  // handle.showDragonBones();
                })
              })
            }
          })
        } else {
          this.showWrongCircle(errorIcon.node, errorMask.node)
          this.g_enableClick = true;
        }
      })

      el.in = (callback) => {
        this.g_cartoon.tweenChange(el.node, {x: el.initX}, 0.5, ()=>{
          callback && callback()
        })
      }

      el.out = (callback) => {
        this.g_cartoon.tweenChange(el.node, {x: el.initX - this.g_canvas.width}, 0.5, ()=>{
          callback && callback()
        })
      }

      el.setContent = (image_url) => {
        this.g_cartoon.tweenChange(imageContainer.node, {scaleX: 0, scaleY: 0}, 0.1, ()=>{
          this.getSpriteFrimeByUrl(image_url, (fr)=>{
            imageContainer.node.getComponent(cc.Sprite).spriteFrame = fr
            this.g_cartoon.tweenChange(imageContainer.node, {scaleX: imageContainer.initScaleX, scaleY: imageContainer.initScaleY}, 0.1)
          })
        })
      }

      if(!dataItem.audio_url) {
        audioEl.node.active = false;
      } else {
        audioEl.node.active = true;
      }

			this.g_cartoon.getCartoonElement(`selected_${order[index]}_speaker`).node.off("click")
      this.g_cartoon.getCartoonElement(`selected_${order[index]}_speaker`).node.on("click", ()=>{
        this.g_cartoon.stopAllAudio()
        this.g_cartoon.stopSoundAnima(audioAni)
        this.g_cartoon.showSoundAnima(audioAni)
        if(!this.m_questionDone) {
          this.g_cartoon.getCartoonElement(`selected_${order[index]}_play`).node.active = true;
        }

        this.g_cartoon.playAudio(dataItem.audio_url, ()=>{
          this.g_cartoon.stopSoundAnima(audioAni)
          this.g_cartoon.getCartoonElement(`selected_${order[index]}_play`).node.active = false;
        })
        
      })

    }
  }

  playQuestion(callback) {
    if(this.m_currentQuestion==0 && this.g_formData.dataArray[this.m_currentQuestion].question.question_audio_url) {
      this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.question_audio_url, ()=>{
        this.m_questionAudioPlayed = true;
        this.g_cartoon.getCartoonElement("question_body_pannel").in(()=>this.playQuestionBody(()=>{
          if(callback) {
            callback()
          }
        }));
      })
    } else {
      this.g_cartoon.getCartoonElement("question_body_pannel").in(()=>this.playQuestionBody(()=>{
        if(callback) {
          callback()
        }
      }));
    }
  }

  playQuestionBody(callback) {
  	console.log("TEST", this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url)
    if(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url) {
      this.g_cartoon.playAudio(this.g_formData.dataArray[this.m_currentQuestion].question.body_audio_url, ()=>{
        if(callback) {
          callback()
        }
      })
    } else {
      if(callback) {
        callback()
      }
    }
  }

  initButtons() {
    let left = this.g_cartoon.getCartoonElement(`buttombutton_left`)
    let right = this.g_cartoon.getCartoonElement(`buttombutton_right`)
    let reload = this.g_cartoon.getCartoonElement(`buttombutton_restart`)
    let close = this.g_cartoon.getCartoonElement(`buttombutton_close`)

    left.disabled = true;
    left.node.opacity = 128;
    right.disabled = false;

    this.g_cartoon.subscribeTouchEvent(left.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      if(left.disabled) {
        return
      }
      this.g_enableClick = false;
      
      jelly(left.node)
      if(this.m_currentQuestion >0) {
        this.m_currentQuestion--
        this.refreshQuestion(()=>{
          this.g_enableClick = true;
        })
      } else {
        this.g_enableClick = true;
      }
    })

    this.g_cartoon.subscribeTouchEvent(right.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      if(right.disabled) {
        return
      }
      jelly(right.node)
      this.g_enableClick = false;
      if(this.m_currentQuestion<this.g_formData.dataArray.length-1) {
        this.m_currentQuestion++
        this.refreshQuestion(()=>{
          this.g_enableClick = true;
        })
      } else {
        this.g_enableClick = true;
      }
    })

    this.g_cartoon.subscribeTouchEvent(reload.key, ()=>{
      if(!this.g_enableClick) {
        console.warn("g_enableClick disabeld!")
        return;
      }
      
      jelly(reload.node)
      this.g_enableClick = false;
      this.refreshQuestion(()=>{
        this.g_enableClick = true;
      })
    })

  }

  maskOthers(index) {
    for(let i=0; i<8; i++) {
      this.g_cartoon.getCartoonElement(`selected_${i+1}_error_mask`).node.active = (index==i)?false:true;
    }
  }

  resetAllSelectedCards() {
    this.m_questionDone = false;
    this.m_questionAudioPlayed = false;
    for(let i=1; i<=8; i++) {
      this.g_cartoon.getCartoonElement(`selected_${i}_highlight`).node.active = false
      this.g_cartoon.getCartoonElement(`selected_${i}_play`).node.active = false
      this.g_cartoon.getCartoonElement(`selected_${i}_image_container`).node.active = true
    }
    this.g_cartoon.getCartoonElement("DragonBones-Container").hide();
    this.g_cartoon.getCartoonElement("question_body_pannel").out();
    // this.g_cartoon.getCartoonElement("question_title_pannel").out()
    this.g_cartoon.getCartoonElement("Center_DragonBones").dragonBones.resetDragonBones()

  }

  initText() {
    this.g_cartoon.getCartoonElement("question_title_pannel_text").node.color = this.g_cartoon.getColor("FFFFFF")
    this.g_cartoon.getCartoonElement("question_title_pannel_text").node.getComponent(cc.Label).string =  this.g_formData.dataArray[this.m_currentQuestion].question.question_text
    this.g_cartoon.getCartoonElement("question_title_pannel_text").node.getComponent(cc.Label).font = this.g_cartoon.getFontFamily("FatMarker")
    this.g_cartoon.getCartoonElement("question_title_pannel_text").node.getComponent(cc.Label).fontSize = 32

    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.color = this.g_cartoon.getColor("ffd75f")
    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.getComponent(cc.Label).string = this.g_formData.dataArray[this.m_currentQuestion].question.body_text
    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.getComponent(cc.Label).font = this.g_cartoon.getFontFamily("BRLNSR_1")
    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.getComponent(cc.Label).fontSize = 42;


    // if( this.g_formData.dataArray[this.m_currentQuestion].textDragonBones &&
    //     this.g_formData.dataArray[this.m_currentQuestion].textDragonBones.skeJsonData.url &&
    //     this.g_formData.dataArray[this.m_currentQuestion].textDragonBones.texJsonData.url &&
    //     this.g_formData.dataArray[this.m_currentQuestion].textDragonBones.texPngData.url) {
    //   this.g_cartoon.getCartoonElement("Text_DragonBones").dragonBones.setDragonBones(this.g_formData.dataArray[this.m_currentQuestion].textDragonBones, (handle)=>{
    //     this.g_cartoon.getCartoonElement("question_body_pannel_text").node.active = false;
    //     handle.showDragonBones(1);
    //   })
    // } else {
    //   this.g_cartoon.getCartoonElement("question_body_pannel_text").node.active = true;
    // }
    this.g_cartoon.getCartoonElement("question_body_pannel_text").node.active = true;

  }

  checkButtonStatus() {
		if(this.m_currentQuestion == 0) {
      this.g_cartoon.getCartoonElement("buttombutton_left").node.opacity = 128;
      this.g_cartoon.getCartoonElement("buttombutton_left").disabled = true;
    } else {
      this.g_cartoon.getCartoonElement("buttombutton_left").node.opacity = 255;
      this.g_cartoon.getCartoonElement("buttombutton_left").disabled = false;
    }

    if(this.m_currentQuestion == this.g_formData.dataArray.length-1) {
      this.g_cartoon.getCartoonElement("buttombutton_right").node.opacity = 128;
      this.g_cartoon.getCartoonElement("buttombutton_right").disabled = true;
    } else {
      this.g_cartoon.getCartoonElement("buttombutton_right").node.opacity = 255;
      this.g_cartoon.getCartoonElement("buttombutton_right").disabled = false;
    }
  }

  refreshQuestion(callback) {
    this.g_cartoon.stopAllAudio()
    this.showMaskLayer(()=>{
    	this.checkButtonStatus()
      this.resetAllSelectedCards()
      this.initSelectedCards();
      this.initText()
      this.initCenterImage();
      this.hideMaskLayer(()=>{
        this.playQuestion(()=>{
          if(callback) {
            callback()
          }
        })
      })
    })
    
  }

  showRightCircle(targetNode, callback) {
    const centerPic = this.g_cartoon.getNodeByPath(`Canvas/center_image`)
    const oldParent = targetNode.node.parent
    const worldPos = oldParent.convertToWorldSpaceAR(cc.v2(targetNode.node.x, targetNode.node.y));
    const localPos = centerPic.convertToNodeSpaceAR(cc.v2(worldPos.x, worldPos.y));
    const picNode = this.g_cartoon.cloneNode(targetNode.node)
    targetNode.node.active = false;
  
    picNode.parent = centerPic;
    picNode.x = localPos.x;
    picNode.y = localPos.y;
  
    const sx = centerPic.width / picNode.width
    const sy = centerPic.height / picNode.height;
    const s = Math.min(sx, sy);

    cc.tween(picNode)
      .to(0.7, {x: 0, y: 0, angle: 360}, {easing: 'sineOut'})
      .delay(0.2)
      .to(1.5, {scale: s, opacity: 0}, {easing: 'cubicOut'})
      .call(() => {
        if(callback) {
          callback()
        }
      })
      .start();
  }
  
  
  showWrongCircle(icon, mask) {
    if (mask.active) {
      return;
    }
    // cc.audioEngine.play(this.audioWrong.clip, false, 0.2)
  	this.g_cartoon.playAudio("error")
    const showIcon = () => {
      cc.tween(icon)
        .to(0.3, {scale: 0.9}, {easing: 'bounceOut'})
        .delay(0.2)
        .to(0.7, {scale: 0}, {easing: 'cubicIn'})
        .call(()=>{
          this.g_cartoon.playAudio("tryagain")
        })
        .start();
    }
  
    const hide = () => {
      mask.opacity = 0;
      cc.tween(mask)
      .to(0.1, {opacity: 255})
      .call(() => {
        showIcon();
      })
      .start()
    }
  
    hide();
    mask.active = true;
  }










  // Common function
  maskLayer = null;
  initMaskLayer() {
    const parentNode = this.g_cartoon.getNodeByPath("Canvas/MaskLayer")
    parentNode.x = cc.winSize.width / 2
    parentNode.y = cc.winSize.height / 2
    const bNode = this.getSprNode('black');
    bNode.scaleX = cc.winSize.width / bNode.width;
    bNode.scaleY = cc.winSize.height / bNode.height;
    bNode.x = 0
    bNode.y = 0
    bNode.parent = cc.find('Canvas');
    bNode.active = false;
    this.maskLayer = bNode;
  }

  showMaskLayer(cb) {
    this.maskLayer.opacity = 0;
    this.maskLayer.active = true;
    cc.tween(this.maskLayer)
      .to(0.5, {opacity: 255}, {easing: 'sineOut'})
      .call(() => {
        cb()
      })
      .start()
  }

  hideMaskLayer(cb = null) {
    this.maskLayer.opacity = 255;
    cc.tween(this.maskLayer)
    .to(0.5, {opacity: 0}, {easing: 'sineIn'})
    .call(() => {
      this.maskLayer.active = false;
      if (cb) {
        cb()
      }
    })
    .start()
  }





  // Common API
  getSpriteFrimeByUrl(url, cb) {
		cc.loader.load({ url }, (err, img) => {
			const spriteFrame = new cc.SpriteFrame(img)
			if (cb) {
				cb(spriteFrame);
			}
		})
  }

  getSpriteFrimeByResName(name) {
    const sf = cc.find('Canvas/res/img/' + name).getComponent(cc.Sprite).spriteFrame;
    // const node = new cc.Node();
    // node.addComponent(cc.Sprite).spriteFrame = sf;
    return sf;
  }

  getSprNode(resName) {
    const sf = cc.find('Canvas/res/img/' + resName).getComponent(cc.Sprite).spriteFrame;
    const node = new cc.Node();
    node.addComponent(cc.Sprite).spriteFrame = sf;
    return node;
  }
}