
import { setTouchEnabled, getTouchEnabled } from './GoldData';

/**
 * Created by rockyl on 2018/8/16.
 */

import { props } from "../props";
import { getIndexFromRC, getRandomArray, getTexture, getTextureByName } from "./utils";
import ObjectPool = engine.ObjectPool;
import GameData from "./gameData";
import EgretRender from "../physics/EgretRender";
import check from "./check";
import { addScore, getlevelTime, getCurLevel, getScore, getlevelMax } from "./goldData";
import createBox from "./createBox";
import createItems from "./createItems";
import { stopStandbyBubblesLeft, startStandbyBubblesLeft, stopStandbyBubblesRight, startStandbyBubblesRight } from "./standbyBubbles";
import createBtns from "./createBtns";
import createBubblePic from "./createBubblePic";
import { bubbleGroup, bubble, bubbleMask, award } from "./collisionConfig";
import { Tool } from './Tools';
import { playBoom } from "./playMovieClip";


export default class GameView extends engine.Container {
  private _bg;
  private _gameNode;
  public _leftBtn;
  public _rightBtn;
  private _light;
  private _basket_top;
  private _basket_bottom;
  private _gameData:GameData;
  public _engine: Matter.Engine;
  public egretRenderContainer: engine.Sprite;
  public _egretRender: EgretRender;
  private _countDown:engine.Sprite;
  private _countDownLabel:engine.Label;
  public _startStandbyBubblesLeft;
  public _startStandbyBubblesRight;
  private _curLevelTime;
  public gameHint:{[name: string]: any} = {};
  private toastRect;
  private toastLabel:engine.Label;
	constructor() {
		super();
  }

  async start(color) {
    let a = new engine.Shape()
    this.addChild(a)
    engine.globalLoader.loadImage('//yun.duiba.com.cn/aurora/assets/66ab48ff49a741f0c93335d4eb0c9e50b7ab6e1e.png', 'bg_dot')
    .then((img)=>{
      a.beginBitmapFill(img,null)
      a.drawRect(0,0,750,1624)
      a.endFill()
    });


    let gameNode = this._gameNode = new engine.Sprite(getTextureByName('机子'));
    gameNode.y = 260;
    this.addChild(gameNode);

    let contPng = new engine.Image(getTextureByName('contPng'));
    contPng.x = (750-contPng.width)/2
    contPng.y = 215;
    this.addChild(contPng);

    let leftBtn = this._leftBtn = new engine.Sprite(getTextureByName('左按钮'));
    leftBtn.anchorY = leftBtn.height-50
    leftBtn.x = 83;
    leftBtn.y = 920;
    gameNode.addChild(leftBtn);

    let rightBtn = this._rightBtn = new engine.Sprite(getTextureByName('右按钮'));
    rightBtn.anchorY = rightBtn.height-50
    rightBtn.x = 400;
    rightBtn.y = 920;
    gameNode.addChild(rightBtn);

    let light = this._light = new engine.Sprite(getTextureByName('灯'));
    light.x = 12;
    light.y = 44;
    gameNode.addChild(light);

    let basket_bottom = this._basket_bottom = new engine.Sprite(getTextureByName('basket_bottom'));
    basket_bottom.x = (contPng.width - basket_bottom.width)/2;
    basket_bottom.y = 85;
    contPng.addChild(basket_bottom);
    let tmpRect = new engine.Rect();
    tmpRect.x = 230
    tmpRect.y = 372
    tmpRect.width = 300;
    tmpRect.height = 300;
    this.addChild(tmpRect);
    basket_bottom.mask = tmpRect;

    let basket_top = this._basket_top = new engine.Sprite(getTextureByName('basket_top'));
    basket_top.x = 287;
    basket_top.y = 485;
    this.addChild(basket_top);

    let glass = this._basket_top = new engine.Sprite(getTextureByName('玻璃'));
    glass.x = (750-glass.width)/2;
    glass.y = 340;
    this.addChild(glass);


    let gameData = this._gameData = new GameData(contPng,color);
    contPng.addChild(gameData);

    //倒计时
    let countDown = this._countDown = new engine.Sprite(getTextureByName('倒计时'));
    countDown.x = 5;
    countDown.y = 180;
    this.addChild(countDown);

    this._curLevelTime = getlevelTime()
    let countDownLabel = this._countDownLabel = Tool.getLabel(this._curLevelTime,48,"#ffffff")
    countDownLabel.x = (countDown.width-countDownLabel.width)/2
    countDownLabel.y = (countDown.height-countDownLabel.height)/2 - 5
    countDown.addChild(countDownLabel);

    this.initGameHint();
   



  //  let rect = this.toastRect = new engine.Rect();
  //  rect.fillColor = 0x000000;
  //  rect.width = 400;
  //  rect.height = 80;
  //  rect.x = (750-400) / 2;
  //  rect.y = 500;
  //  rect.alpha = 0;
  //  this.addChild(rect);

  //  let toast = this.toastLabel = Tool.getLabel(``,28,"#28c1ec",false)
  //  toast.x = (rect.width - toast.width) / 2;
  //  toast.y = (rect.height - toast.height) / 2;
  //  toast.fillColor = 0xffffff;
  //  rect.addChild(toast);

   this.startHandle();
   this.levelHint();
  }
  private _lvbg;
  private _lv:engine.Sprite;
  private _lv_common;
  private _lv_label:engine.Label;
  
  levelHint(){
    let lvBg = this._lvbg = new engine.Rect();
    lvBg.fillColor = 0x000000;
    lvBg.alpha = 0.7;
    lvBg.width = 750;
    lvBg.height = 1624;
    lvBg.x = lvBg.y = 0;
    lvBg.visible = false;
    this.addChild(lvBg);

    let lv_common = this._lv_common = new engine.Sprite(getTextureByName('lv_common'));
    lv_common.x = (750-lv_common.width)/2;
    lv_common.y = 500;
    lv_common.visible = false;
    this.addChild(lv_common);

    let lv1 = this._lv = new engine.Sprite(getTextureByName('lv1'));
    lv1.anchorTexture.set(0.5,0.5)
    lv1.x = lv_common.width/2;
    lv1.y = 80;
    lv_common.addChild(lv1);

    let lv1_label = this._lv_label = Tool.getLabel(`5`,38,"#28c1ec",true,engine.TEXT_ALIGN.CENTER)
    lv1_label.width = 100;
    lv1_label.x = 205;
    lv1_label.y = 205;
    lv1_label.fillColor = 0xffffff;
    lv_common.addChild(lv1_label);

    //this.lvArray.push(lv_common);

  }
  initGameHint(){
    //['great', 'cool', 'perfect', 'awesome', 'unbelievable']
    let awesome = new engine.Sprite(getTextureByName('awesome'));
    awesome.anchorTexture.set(0.5,0.5);
    awesome.x = 520;
    awesome.y = 490;
    awesome.alpha = 0;
    this.addChild(awesome);
    this.gameHint['awesome'] = awesome;

    let cool = new engine.Sprite(getTextureByName('cool'));
    cool.anchorTexture.set(0.5,0.5);
    cool.x = 520;
    cool.y = 490;
    cool.alpha = 0;
    this.addChild(cool);
    this.gameHint['cool'] = cool;

    let good = new engine.Sprite(getTextureByName('good'));
    good.anchorTexture.set(0.5,0.5);
    good.x = 520;
    good.y = 490;
    good.alpha = 0;
    this.addChild(good);
    this.gameHint['good'] = good;

    let great = new engine.Sprite(getTextureByName('great'));
    great.anchorTexture.set(0.5,0.5);
    great.x = 520;
    great.y = 490;
    great.alpha = 0;
    this.addChild(great);
    this.gameHint['great'] = great;

    let perfect = new engine.Sprite(getTextureByName('perfect'));
    perfect.anchorTexture.set(0.5,0.5);
    perfect.x = 530;
    perfect.y = 490;
    perfect.alpha = 0;
    this.addChild(perfect);
    this.gameHint['perfect'] = perfect;

    let unbelievable = new engine.Sprite(getTextureByName('unbelievable'));
    unbelievable.anchorTexture.set(0.5,0.5);
    unbelievable.x = 480;
    unbelievable.y = 460;
    unbelievable.alpha = 0;
    this.addChild(unbelievable);
    this.gameHint['unbelievable'] = unbelievable;
  }
  startNextLevel(){
    this.clearAwardBody()
    this.playLevelAni()
    setTouchEnabled(true);
    createItems(this);
    this._gameData.scorePosUpdate();
    this._gameData.resetMask();
    this._gameData.levelUpdate();
    this._curLevelTime = getlevelTime()
    this._countDownLabel.text = this._curLevelTime;
    this._countDownLabel.x = (this._countDown.width-this._countDownLabel.width)/2
    this.runEngine();
  }
  themeChange(data){
    this._countDown.texture = engine.Texture.fromImage(data.gameCountdownImage);

    this._leftBtn.texture = engine.Texture.fromImage(data.leftButtonImage);
    this._leftBtn.anchorY = this._leftBtn.height-50
    this._leftBtn.x = 83;
    this._leftBtn.y = 920;

    this._rightBtn.texture = engine.Texture.fromImage(data.rightButtonImage);
    this._rightBtn.anchorY = this._rightBtn.height-50
    this._rightBtn.x = 400;
    this._rightBtn.y = 920;
  }
  revive(){
    setTouchEnabled(true);
    this.runEngine();
  }
  startHandle(){
    //创建引擎
    const engineMatter = Matter.Engine.create();
    this._engine = engineMatter;
    this._engine.world.gravity.y = 0.2;

    //创建egret渲染
    this.egretRenderContainer = new engine.Sprite();
    this.addChild(this.egretRenderContainer);
    this._egretRender = new EgretRender(this.egretRenderContainer, this._engine);
    const options: any = {
        width: 750,
        height: 1624,
        wireframes: !1,
    };

    const render = Matter.Render.create({
        element: document.getElementById('debugCanvas'),
        engine: engineMatter,
        options: options
    });
    Matter.Render.run(render);
    this.runGame();
  }
  addForce = false;
    stageX = 0;
    stageY = 0;
  runGame(){
    createBox(this);
    Matter.Events.on(this._engine, 'beforeUpdate', () => {
      if (!this.addForce) return
      this.addForce = false;
      const isleft = this.stageX < 375;
      const start = isleft ? { x: 180, y: 1050 } : { x: 560, y: 1050 };
      const scale = 2.2;
      for (let i = 0; i < 15; i++) {
          setTimeout(() => {
              const r = this.random(10, 14);
              let bubblePic;
              bubblePic = createBubblePic(r);//默认球的尺寸100
              const basex = 0.02;
              const xoffset = 0.007;
              const fx = isleft ? this.random(-basex, basex) : this.random(-basex, basex);
              const padding = 50;
              const startx = this.random(start.x - padding, start.x + padding);
              if (fx < -xoffset || fx > xoffset) bubblePic = null;
              const body = this._egretRender.circle(startx, start.y, r, bubblePic,
                  {
                      density: 0.001 * 3,
                      restitution: 1,
                      force: { x: fx * scale, y: -0.02 * scale },
                      collisionFilter: { group: bubbleGroup, category: bubble, mask: bubbleMask }
                  }
              );

              setTimeout(() => {
                  this._egretRender.remove(body);
              }, 1000);
          }, Math.random() * 200);
      }
      for (let j = 0; j < 1; j++) {
          const start = isleft ? { x: 180 + 50, y: 1050 + 30 } : { x: 560 - 50, y: 1050 + 30 };
          const r = this.random(10, 14);
          const body = this._egretRender.circle(start.x, start.y, r, null,
              {
                  density: 0.001 * 3,
                  restitution: 1,
                  force: { x: (isleft ? 1 : -1) * 0.02 * 1.7, y: 0 },
                  collisionFilter: { group: bubbleGroup, category: bubble, mask: bubbleMask }
              }
          );

          setTimeout(() => {
              this._egretRender.remove(body);
          }, 1000);
      }
      
  });

    this._leftBtn.addEventListener(engine.MouseEvent.CLICK, (e: engine.MouseEvent) => {
        if(!getTouchEnabled())return;
        this.addForce = true;
        this.stageX = e.stageX;
        stopStandbyBubblesLeft();
        clearTimeout(this._startStandbyBubblesLeft);
        this._startStandbyBubblesLeft = setTimeout(() => {
            startStandbyBubblesLeft(this._egretRender);
        }, 1000);
    }, this);

    this._rightBtn.addEventListener(engine.MouseEvent.CLICK, (e: engine.MouseEvent) => {
        if(!getTouchEnabled())return;
        this.addForce = true;
        this.stageX = e.stageX;
        stopStandbyBubblesRight();
        clearTimeout(this._startStandbyBubblesRight);
        this._startStandbyBubblesRight = setTimeout(() => {
          startStandbyBubblesRight(this._egretRender);
        }, 1000);
    }, this);
    createBtns(this)
    startStandbyBubblesLeft(this._egretRender);
    startStandbyBubblesRight(this._egretRender);

  }
  //帧处理 
  private lastTime;
  private _frameCount = 0;
  enterFrame(){
    var now = Date.now();
    var deltaTime = this.lastTime ? now - this.lastTime : 16.7;
    this.lastTime = now;
    this._frameCount += deltaTime;
    if(this._frameCount>=1000){
      this._frameCount = 0;
      this.updateCountDown();
    }
    if(deltaTime > 20)
    deltaTime = 20
    Matter.Engine.update(this._engine, deltaTime);
    this._egretRender.run();
    check(this);
    return false;
  }
  random(start, end){
    const n = end - start; 
    return Math.random() * n + start;
  }
  runEngine(){
    engine.gameStage.addEventListener(engine.Event.ENTER_FRAME, this.enterFrame, this)
  }
  updateCountDown(){
    this._curLevelTime --
    this._countDownLabel.text = this._curLevelTime;
    this._countDownLabel.x = (this._countDown.width-this._countDownLabel.width)/2
    if(this._curLevelTime <= 0)
    {
      this.end();
      console.log('时间结束');
    }

  }
  onBoom(){
    this.end();
 
  }
   addScore(): any {
      addScore(1)
      if(getScore() >= getlevelMax()){
        setTouchEnabled(false);
        engine.gameStage.removeEventListener(engine.Event.ENTER_FRAME, this.enterFrame, this)
        engine.globalEvent.dispatchEvent('seabed-game-success',{level:getCurLevel(),score:getScore()})
      }

      this._gameData.scorePosUpdate();
    }
    playLevelAni(){
      const lv = getCurLevel();

      this._lv.texture = getTextureByName(`lv${lv}`)
      this._lv_label.text = getlevelMax()+'';
      this._lvbg.visible = true;
      this._lv_common.visible = true;
      engine.Tween.get(this._lv_common).set({ y: 500 - 1624 }).to({ y: 500 }, 700, engine.Ease.backOut)
          .wait(1000).to({ y: 1624 + 500 }, 500, engine.Ease.backIn)
          .call(()=>{
            this._lvbg.visible = false;
          });
      //engine.Tween.get(this['lvbg']).wait(700 + 1000).to({ alpha: 0 }, 500);
    }
    
    clearAwardBody() {
      const bodies = Matter.Composite.allBodies(this._engine.world);
      const isAward = (i: Matter.Body) => { return i.collisionFilter.group == award }
      bodies.forEach(i => {
          if (isAward(i)) this._egretRender.remove(i);
      })
  }

  end(){
    engine.gameStage.removeEventListener(engine.Event.ENTER_FRAME, this.enterFrame, this)
    engine.globalEvent.dispatchEvent('seabed-game-fail',{level:getCurLevel(),score:getScore(),time:this._curLevelTime})
    setTouchEnabled(false);
  }
}