import Cartoon from "./Cartoon"
import defaultData from "./defaultData"
import { jelly, randomSortByArr } 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;
  g_imageResList = [];
  g_audioResList = [];
  g_animaResList = [];
  g_properties = {};

  m_currentQuestion = -1;
  m_gameEnd = false;
  m_firstEnter = true;
  m_options = []
  m_avaliableAI = 0;
  m_curLeftAnswerPoi = 0;
  m_curMiddleAnswerPoi = 0;
  m_curRightAnswerPoi = 0;

  m_maxScale = 0.7;
  constructor(formData, systemOption) {
    this.g_systemOption = systemOption;
    this.g_imageResList = this.g_systemOption.imageResList;
    this.g_audioResList = this.g_systemOption.audioResList;
    this.g_animaResList = this.g_systemOption.animaResList;
    this.g_properties = this.g_systemOption.properties;

    this.g_canvas = cc.find('Canvas');
    this.g_cartoon = new Cartoon(cc);

    // if(!formData.contentObj.options || formData.contentObj.options.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.disableClick("Sysyem_init")
    this.g_cartoon.initLocalAudios([])
    // this.initMaskLayer();
    
    this.initNodes();
    this.initBg();
    this.resetPosition();

    this.initBubbles();

    this.g_cartoon.initDragEvent()
    this.enableClick("Sysyem_init");
    this.hideAir();
    this.systemTick();

    setTimeout(() => {
      this.releaseBubbles()
    }, 500);

    cc.view.setResizeCallback(() => {
      this.initBg();
      this.resetPosition();
   });

  }

  systemTick() {
    let maxNum = this.bubblesAll.length;
    let maxX = cc.winSize.width / 2;
    let maxY = cc.winSize.height / 2;
    setInterval(()=>{
      this.bubblesAll.forEach((bubble, index_x)=>{
        if(bubble.move.enable && !bubble.move.fix) {
          bubble.move.x += bubble.move.vX
          bubble.move.y += bubble.move.vY
          if(bubble.move.scale<this.m_maxScale) {
            bubble.move.scale += 0.1;
          } else {
            bubble.move.scale = this.m_maxScale
          }
          
          bubble.node.scaleX = bubble.move.scale;
          bubble.node.scaleY = bubble.move.scale;

          if (bubble.move.x >= maxX - bubble.move.r * bubble.move.scale) {
            bubble.move.x = maxX - bubble.move.r * bubble.move.scale;
            bubble.move.vX = -bubble.move.vX;
            bubble.move.lastId = null;
          }
          if (bubble.move.x <= -maxX + bubble.move.r * bubble.move.scale) {
            bubble.move.x = -maxX + bubble.move.r * bubble.move.scale;
            bubble.move.vX = -bubble.move.vX;
            bubble.move.lastId = null;
          }
          if (bubble.move.y >= maxY - bubble.move.r * bubble.move.scale) {
            bubble.move.y = maxY - bubble.move.r * bubble.move.scale;
            bubble.move.vY = -bubble.move.vY;
            bubble.move.lastId = null;
          }
          if (bubble.move.y <= -maxY + bubble.move.r * bubble.move.scale) {
            bubble.move.y = -maxY + bubble.move.r * bubble.move.scale;
            bubble.move.vY = -	bubble.move.vY;
            bubble.move.lastId = null;
          }
  
          bubble.node.x = bubble.move.x
          bubble.node.y = bubble.move.y
          
          for (var j = 0; j < maxNum; j++) {
            if (j !== index_x) {
              if (Math.round(Math.pow(this.bubblesAll[index_x].node.x - this.bubblesAll[j].node.x, 2) +
                Math.pow(this.bubblesAll[index_x].node.y - this.bubblesAll[j].node.y, 2)) <=
                Math.round(Math.pow(this.bubblesAll[index_x].move.r * this.bubblesAll[index_x].move.scale + this.bubblesAll[j].move.r * this.bubblesAll[j].move.scale, 2))) {
  
                var tempX = this.bubblesAll[index_x].move.vX;
                var tempY = this.bubblesAll[index_x].move.vY;
                if(this.bubblesAll[index_x].move.lastId != this.bubblesAll[j].move.id) {
                  this.bubblesAll[index_x].move.lastId = this.bubblesAll[j].move.id
                  if(this.bubblesAll[j].move.fix) {
                    this.bubblesAll[index_x].move.vX = -this.bubblesAll[index_x].move.vX;
                    this.bubblesAll[index_x].move.vY = -this.bubblesAll[index_x].move.vY;
                  } else {
                    this.bubblesAll[index_x].move.vX = this.bubblesAll[j].move.vX;
                    this.bubblesAll[j].move.vX = tempX;
                    this.bubblesAll[index_x].move.vY = this.bubblesAll[j].move.vY;
                    this.bubblesAll[j].move.vY = tempY;
                  }
                }
              }
            }
          }
        }
      })
      
    }, 30)
  }

  initNodes() {
    this.g_cartoon.initCartoonElement("background", this.g_cartoon.getNodeByPath(`Canvas/background/background`));
    this.g_cartoon.initCartoonElement("lion", this.g_cartoon.getNodeByPath(`Canvas/lion`));

    const bubbleParent = this.g_cartoon.getNodeByPath(`Canvas/bubble_group`)
    for(let i=0; i<6; i++) {
      const bubble = cc.instantiate(this.g_systemOption.prefabs.bubble);
      bubble.parent = bubbleParent;
      console.log(bubble)
      this.g_cartoon.setCartoonElement(`bubble_${i}`, bubble)
    }
  }

  initBg() {
    const bgMain = this.g_cartoon.getCartoonElement("background")
    // if(this.g_formData.bg.type == "custome" && this.g_formData.bg.image_url) {
    //   this.g_cartoon.mountImageToNode(this.g_formData.bg.image_url, bgMain.node, cc.winSize.width, cc.winSize.height, true);
    // } else {
      bgMain.node.width = cc.winSize.width
      bgMain.node.height = cc.winSize.height
    // }
  }

  bubblesAll = []
  initBubbles() {
    for(let i=0; i<6; i++) {
      const bubble = this.g_cartoon.getCartoonElement(`bubble_${i}`)
      bubble.move = {
        r: 100, x: 0, y: 0, vX: 1, vY: 1.3, enable: false, fix: false, scale: 0, id: i, lastId: null
      }
      bubble.node.scaleX = 0;
      bubble.node.scaleY = 0;

      bubble.node.x = 0;
      bubble.node.y = -2000;
      
      this.bubblesAll.push(bubble)
    }
  }

  resetPosition() {
    let node = this.g_cartoon.getNodeByPath(`Canvas/speaker`)
    node.x = -cc.winSize.width / 2 + 100
    node.y = -cc.winSize.height / 2 + 100
    this.bubblesAll.push({node: node, move: {
      r: 50, x: node.x, y: node.y, vX: 0, vY: 0, enable: true, fix: true, scale: 1, id: 999, lastId: null
    }})

    node = this.g_cartoon.getNodeByPath(`Canvas/btn_back`)
    node.x = -cc.winSize.width / 2 + 60
    node.y = cc.winSize.height / 2 - 50
    this.bubblesAll.push({node: node, move: {
      r: 40, x: node.x, y: node.y, vX: 0, vY: 0, enable: true, fix: true, scale: 1, id: 998, lastId: null
    }})

    node = this.g_cartoon.getNodeByPath(`Canvas/btn_restart`)
    node.x = 0
    node.y = 20
    // this.bubblesAll.push({node: node, move: {
    //   r: 90, x: node.x, y: node.y, vX: 0, vY: 0, enable: true, fix: true, scale: 1
    // }})

    node = this.g_cartoon.getNodeByPath(`Canvas/lion`)
    node.x = cc.winSize.width / 2 - 150
    node.y = -cc.winSize.height / 2 + 170
    this.bubblesAll.push({node: node, move: {
      r: 90, x: node.x, y: node.y, vX: 0, vY: 0, enable: true, fix: true, scale: 1, id: 997, lastId: null
    }})
  }

  releaseBubbles() {
    let startx = cc.winSize.width / 2 - 350
    let starty = -cc.winSize.height / 2 + 350
    const vArr = [
      {vX: -5, vY: 1 }, {vX: -5, vY: 2 }, {vX: -5, vY: 1 }
    ]

    // const pos = [
    //   {x: }
    // ]
    this.bubblesAll.forEach((bubble, index) => {
      setTimeout(() => {
        if(!bubble.move.fix) {
          bubble.node.x = startx
          bubble.node.y = starty
          bubble.move.x = startx
          bubble.move.y = starty
          bubble.move.vX =  vArr[index%3].vX
          bubble.move.vY = vArr[index%3].vY
          bubble.move.scale = 0.3;
          bubble.node.scaleX = bubble.move.scale;
          bubble.node.scaleY = bubble.move.scale;
          // console.log(bubble.move.vX, bubble.move.vY)
          bubble.move.enable = true;
          setTimeout(() => {
            
            bubble.move.vX = -1 * (Math.ceil(Math.random()*10)/10)
          }, 1000);
        }
      }, 1500 * index);
    })
  }



  










  // Common function
  maskLayer = null;
  initMaskLayer() {
    const parentNode = this.g_cartoon.getNodeByPath("MaskLayer")
    parentNode.x = cc.winSize.width / 2
    parentNode.y = cc.winSize.height / 2
    const bNode = this.getSprNodeByResName('black');
    bNode.scaleX = cc.winSize.width / bNode.width;
    bNode.scaleY = cc.winSize.height / bNode.height;
    bNode.x = 0
    bNode.y = 0
    parentNode.setSiblingIndex(255)
    bNode.parent = cc.find('MaskLayer');
    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()
  }

  startTwinkleAnime(speakerBase, path, len, speed = 0.2) {
    const speakers = [];
    for (let index = 0; index < len; index++) {
      const node = cc.find(`${path}_${index}`);
      speakers.push(node);
    }
    let currentIdx = 0;
    cc.tween(speakerBase)
      .call(() => {
        speakers.forEach(node => node.active = false);
        speakers[currentIdx % speakers.length].active = true;
        currentIdx++;
      })
      .delay(speed)
      .union()
      .repeatForever()
      .start();
  }

  stopTwinkleAnime(speakerBase, path, len) {
    speakerBase.stopAllActions();
    for (let index = 0; index < len; index++) {
      const node = cc.find(`${path}_${index}`);
      node.active = false;
    }
    const node0 = cc.find(`${path}_0`);
    node0.active = true;
  }

  // Common API
  getSprNodeByUrl(resName) {
    return new Promise((resolve, reject) => {
      cc.assetManager.loadRemote(url, (err, img) => {
        const node = new cc.Node();
        const spriteFrame = new cc.SpriteFrame(img)
        node.addComponent(cc.Sprite).spriteFrame = sf;
        resolve(node)
      })
    })
  }

  getSprNodeByResName(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;
  }



  // Sysyem function
  hideAir() {
    if (window && window["air"]) {
      window["air"].hideAirClassLoading();
    }
    cc.debug.setDisplayStats(false);
  }

  checkClickEnable(eventName) {
    if(this.g_enableClick) {
      return true;
    } else {
      // console.log(`Click disabled by event [${this.g_disableClickEventName}]!`)
      return false;
    }
  }

  disableClick(eventName) {
    this.g_enableClick = false;
    this.g_disableClickEventName = eventName
    // console.log(`Click disabled! [${eventName}]`)
  }

  enableClick(eventName) {
    this.g_enableClick = true;
    this.g_disableClickEventName = ""
    // console.log(`Click enabled! [${eventName}]`)
  }

}
