import { Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener } from '@angular/core';

import {
  Label,
  MySprite, tweenChange,

} from './Unit';
import { res, resAudio } from './resources';

import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

import TWEEN from '@tweenjs/tween.js';

import { Stage, Mission } from './Stage';


@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.css']
})
export class PlayComponent implements OnInit, OnDestroy {

  @ViewChild('canvas', { static: true }) canvas: ElementRef;
  @ViewChild('wrap', { static: true }) wrap: ElementRef;

  // 数据
  data;

  ctx;

  canvasWidth = 1280; // canvas实际宽度
  canvasHeight = 720; // canvas实际高度

  canvasBaseW = 1280; // canvas 资源预设宽度
  canvasBaseH = 720;  // canvas 资源预设高度

  mx; // 点击x坐标
  my; // 点击y坐标


  // 资源
  rawImages = new Map(res);
  rawAudios = new Map(resAudio);

  images = new Map();

  animationId: any;
  winResizeEventStream = new Subject();

  audioObj = {};

  renderArr;
  mapScale = 1;

  canvasLeft;
  canvasTop;

  saveKey = 'PU-11';


  btnLeft;
  btnRight;

  canTouch = true;

  theme;

  stage: Stage;

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.winResizeEventStream.next();
  }


  ngOnInit() {

    this.data = {};

    // 获取数据
    const getData = (<any>window).courseware.getData;
    getData((data) => {

      if (data && typeof data == 'object') {
        this.data = data;
      }
      console.log('data:' , data);

      // 初始化 各事件监听
      this.initListener();

      // 若无数据 则为预览模式 需要填充一些默认数据用来显示
      this.initDefaultData();

      // 初始化 音频资源
      this.initAudio();
      // 初始化 图片资源
      this.initImg();
      // 开始预加载资源
      this.load();

    }, this.saveKey);

  }

  ngOnDestroy() {
    window['curCtx'] = null;
    window.cancelAnimationFrame(this.animationId);
  }


  load() {

    // 预加载资源
    this.loadResources().then(() => {
      window["air"].hideAirClassLoading(this.saveKey, this.data);
  
      this.init();
      this.update();
    });
  }


  init() {

    this.initCtx();
    this.initData();
    this.initView();
  }

  initCtx() {
    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;
    this.canvas.nativeElement.width = this.wrap.nativeElement.clientWidth;
    this.canvas.nativeElement.height = this.wrap.nativeElement.clientHeight;


    this.ctx = this.canvas.nativeElement.getContext('2d');
    this.canvas.nativeElement.width = this.canvasWidth;
    this.canvas.nativeElement.height = this.canvasHeight;

    window['curCtx'] = this.ctx;
  }






  updateItem(item) {
    if (item) {
      item.update();
    }
  }

  updateArr(arr) {
    if (!arr) {
      return;
    }
    for (let i = 0; i < arr.length; i++) {
      arr[i].update(this);
    }
  }







  initListener() {

    this.winResizeEventStream
      .pipe(debounceTime(500))
      .subscribe(data => {
        this.renderAfterResize();
      });


    // ---------------------------------------------
    const setParentOffset = () => {
      const rect = this.canvas.nativeElement.getBoundingClientRect();
      this.canvasLeft = rect.left;
      this.canvasTop = rect.top;
    };
    const setMxMyByTouch = (event) => {
      if (event.touches.length <= 0) {
        return;
      }
      if (this.canvasLeft == null) {
        setParentOffset();
      }
      this.mx = event.touches[0].pageX - this.canvasLeft;
      this.my = event.touches[0].pageY - this.canvasTop;
    };

    const setMxMyByMouse = (event) => {
      this.mx = event.offsetX;
      this.my = event.offsetY;
    };
    // ---------------------------------------------


    let firstTouch = true;

    const touchDownFunc = (e) => {
      if (firstTouch) {
        firstTouch = false;
        removeMouseListener();
      }
      setMxMyByTouch(e);
      this.mapDown(e);
    };
    const touchMoveFunc = (e) => {
      setMxMyByTouch(e);
      this.mapMove(e);
    };
    const touchUpFunc = (e) => {
      setMxMyByTouch(e);
      this.mapUp(e);
    };

    const mouseDownFunc = (e) => {
      if (firstTouch) {
        firstTouch = false;
        removeTouchListener();
      }
      setMxMyByMouse(e);
      this.mapDown(e);
    };
    const mouseMoveFunc = (e) => {
      setMxMyByMouse(e);
      this.mapMove(e);
    };
    const mouseUpFunc = (e) => {
      setMxMyByMouse(e);
      this.mapUp(e);
    };


    const element = this.canvas.nativeElement;

    const addTouchListener = () => {
      element.addEventListener('touchstart', touchDownFunc);
      element.addEventListener('touchmove', touchMoveFunc);
      element.addEventListener('touchend', touchUpFunc);
      element.addEventListener('touchcancel', touchUpFunc);
    };
    const removeTouchListener = () => {
      element.removeEventListener('touchstart', touchDownFunc);
      element.removeEventListener('touchmove', touchMoveFunc);
      element.removeEventListener('touchend', touchUpFunc);
      element.removeEventListener('touchcancel', touchUpFunc);
    };

    const addMouseListener = () => {
      element.addEventListener('mousedown', mouseDownFunc);
      element.addEventListener('mousemove', mouseMoveFunc);
      element.addEventListener('mouseup', mouseUpFunc);
    };
    const removeMouseListener = () => {
      element.removeEventListener('mousedown', mouseDownFunc);
      element.removeEventListener('mousemove', mouseMoveFunc);
      element.removeEventListener('mouseup', mouseUpFunc);
    };

    addMouseListener();
    addTouchListener();
  }


  playAudio(key, now = false, callback = null) {

    const audio = this.audioObj[key];
    if (audio) {
      if (now) {
        audio.pause();
        audio.currentTime = 0;
      }

      if (callback) {
        audio.onended = () => {
          callback();
        };
      }
      audio.play();
    }
  }



  loadResources() {
    const pr = [];
    this.rawImages.forEach((value, key) => {// 预加载图片

      const p = this.preload(value)
        .then(img => {
          this.images.set(key, img);
        })
        .catch(err => console.log(err));

      pr.push(p);
    });

    this.rawAudios.forEach((value, key) => {// 预加载音频

      const a = this.preloadAudio(value)
        .then(() => {
          // this.images.set(key, img);
        })
        .catch(err => console.log(err));

      pr.push(a);
    });
    return Promise.all(pr);
  }

  preload(url) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      // img.crossOrigin = "anonymous";
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = url;
    });
  }

  preloadAudio(url) {
    return new Promise((resolve, reject) => {
      const audio = new Audio();
      audio.oncanplay = (a) => {
        resolve();
      };
      audio.onerror = () => {
        reject();
      };
      audio.src = url;
      audio.load();
    });
  }


  renderAfterResize() {
    this.canvasWidth = this.wrap.nativeElement.clientWidth;
    this.canvasHeight = this.wrap.nativeElement.clientHeight;
    this.init();
  }





  checkClickTarget(target) {

    const rect = target.getBoundingBox();

    if (this.checkPointInRect(this.mx, this.my, rect)) {
      return true;
    }
    return false;
  }

  getWorlRect(target) {

    let rect = target.getBoundingBox();

    if (target.parent) {

      const pRect = this.getWorlRect(target.parent);
      rect.x += pRect.x;
      rect.y += pRect.y;
    }
    return rect;
  }

  checkPointInRect(x, y, rect) {
    if (x >= rect.x && x <= rect.x + rect.width) {
      if (y >= rect.y && y <= rect.y + rect.height) {
        return true;
      }
    }
    return false;
  }





  addUrlToAudioObj(key, url = null, vlomue = 1, loop = false, callback = null) {

    const audioObj = this.audioObj;

    if (url == null) {
      url = key;
    }

    this.rawAudios.set(key, url);

    const audio = new Audio();
    audio.src = url;
    audio.load();
    audio.loop = loop;
    audio.volume = vlomue;

    audioObj[key] = audio;

    if (callback) {
      audio.onended = () => {
        callback();
      };
    }
  }

  addUrlToImages(url) {
    this.rawImages.set(url, url);
  }






  // ======================================================编写区域==========================================================================





  /**
   * 添加默认数据 便于无数据时的展示
   */
  initDefaultData() {

    if (!this.data.stageItemArr) {
      this.data.stageItemArr = [];

      this.data.stageItemArr.push(this.getDefaultStageItem());
    }

    if (!this.data.theme) {
      this.data.theme = '1';
    }
  }


  /**
   * 添加预加载图片
   */
  initImg() {

    for (let i = 0; i < this.data.stageItemArr.length; ++i) {
      let stageItem = this.data.stageItemArr[i];

      if (stageItem.imgUrl) {
        this.addUrlToImages(stageItem.imgUrl);
      }
    }
  }

  /**
   * 添加预加载音频
   */
  initAudio() {

    // 音效
    this.addUrlToAudioObj('click', this.rawAudios.get('click'), 0.3);

  }



  /**
   * 初始化数据
   */
  initData() {

    const sx = this.canvasWidth / this.canvasBaseW;
    const sy = this.canvasHeight / this.canvasBaseH;
    const s = Math.min(sx, sy);
    this.mapScale = s;


    this.renderArr = [];

    this.theme = this.data.theme + "_";

  }



  /**
   * 初始化试图
   */
  initView() {


    this.initPic();

    this.initStage();

    this.initBottomPart();

    this.stage.showNext(()=>{
      this.showBtn();
    });
  }

  initBottomPart() {

    const btnLeft = new MySprite();
    btnLeft.init(this.images.get(this.theme + 'btn_left'));
    btnLeft.x = 158 * this.mapScale;
    btnLeft.y = this.canvasHeight - 100 * this.mapScale;
    btnLeft.alpha = 0;
    btnLeft.setScaleXY(this.mapScale);

    this.renderArr.push(btnLeft);

    this.btnLeft = btnLeft;



    const btnRight = new MySprite();
    btnRight.init(this.images.get(this.theme + 'btn_right'));
    btnRight.x = this.canvasWidth - 118 * this.mapScale;
    btnRight.y = btnLeft.y;
    btnRight.setScaleXY(this.mapScale);
    btnRight.alpha = 0;
    this.renderArr.push(btnRight);

    this.btnRight = btnRight;
  }

  initPic() {

    const bg = new MySprite();
    bg.init(this.images.get(this.theme + "bg"));
    const sx = this.canvasWidth / bg.width;
    const sy = this.canvasHeight / bg.height;
    const s = Math.max(sx, sy);
    bg.setScaleXY(s);
    bg.x = this.canvasWidth / 2;
    bg.y = this.canvasHeight / 2;
    this.renderArr.push(bg);

    const l_middle_1 = new MySprite();
    l_middle_1.init(this.images.get(this.theme + "l_middle_1"));
    l_middle_1.setScaleXY(this.mapScale);
    l_middle_1.x = l_middle_1.getBoundingBox().width / 2 - 25 * this.mapScale;
    l_middle_1.y = 10 * this.mapScale + l_middle_1.getBoundingBox().height / 2;
    this.renderArr.push(l_middle_1);

    const l_middle_2 = new MySprite();
    l_middle_2.init(this.images.get(this.theme + "l_middle_2"));
    l_middle_2.setScaleXY(this.mapScale);
    l_middle_2.x = l_middle_1.getBoundingBox().width / 2 - 30 * this.mapScale;
    l_middle_2.y = 300 * this.mapScale + l_middle_2.getBoundingBox().height / 2;;
    this.renderArr.push(l_middle_2);

    const pencil = new MySprite();
    pencil.init(this.images.get(this.theme + "pencil"));
    pencil.setScaleXY(this.mapScale);
    pencil.x = pencil.getBoundingBox().width / 2 - 55 * this.mapScale;
    pencil.y = this.canvasHeight - pencil.getBoundingBox().height / 2;
    this.renderArr.push(pencil);

    const r_middle = new MySprite();
    r_middle.init(this.images.get(this.theme + "r_middle"));
    r_middle.setScaleXY(this.mapScale);
    r_middle.x = this.canvasWidth - r_middle.getBoundingBox().width / 2 + 80 * this.mapScale;
    r_middle.y = this.canvasHeight / 2;
    this.renderArr.push(r_middle);

    const r_bottom = new MySprite();
    r_bottom.init(this.images.get(this.theme + "r_bottom"));
    r_bottom.setScaleXY(this.mapScale);
    r_bottom.x = this.canvasWidth - r_bottom.getBoundingBox().width / 2 + 30 * this.mapScale;
    r_bottom.y = this.canvasHeight - r_bottom.getBoundingBox().height / 2;
    this.renderArr.push(r_bottom);
  }

  initStage() {

    const stage = new Stage(this.images, this.audioObj, this.mapScale, this.mapScale);
    stage.init(this.theme);
    stage.bg.x = (this.canvasWidth - stage.width) / 2;
    stage.bg.y = (this.canvasHeight - stage.height) / 2 + 50 * this.mapScale;
    this.renderArr.push(stage.bg);
    stage.setStageContent(this.data.stageItemArr);
    this.stage = stage;

    const mission = new Mission(this.images, this.audioObj, this.mapScale, this.mapScale);
    mission.init(this.theme);
    mission.bg.x = -50 * this.mapScale;
    mission.bg.y = 67 * this.mapScale;
    this.renderArr.push(mission.bg);
    this.stage.mission = mission;
  }


  btnLeftClicked() {

    this.lastPage();
  }

  btnRightClicked() {

    this.nextPage();
  }

  lastPage() {

    this.canTouch = false;

    this.stage.showLast(() => {
      this.canTouch = true;
      this.showBtn();
    });

  }

  nextPage() {

    this.canTouch = false;

    this.stage.showNext(() => {
      this.canTouch = true;

      this.showBtn();
      
    });

  }

  showBtn(){
    if(this.stage.curIndex > 0){
      this.btnLeft.alpha = 1;
    }
    else{
      this.btnLeft.alpha = 0;
    }

    if(this.stage.curIndex < this.stage.stageContentArr.length - 1){
      this.btnRight.alpha = 1;
    }
    else{
      this.btnRight.alpha = 0;
    }
  }





  mapDown(event) {

    if (!this.canTouch) {
      return;
    }

    if (this.checkClickTarget(this.btnLeft)) {
      this.btnLeftClicked();
      return;
    }

    if (this.checkClickTarget(this.btnRight)) {
      this.btnRightClicked();
      return;
    }

  }

  mapMove(event) {

  }

  mapUp(event) {

  }



  update() {

    // ----------------------------------------------------------
    this.animationId = window.requestAnimationFrame(this.update.bind(this));
    // 清除画布内容
    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    // tween 更新动画
    TWEEN.update();
    // ----------------------------------------------------------



    this.updateArr(this.renderArr);


  }

  getDefaultStageItem() {
    const stageItem = {
      index: '1',
      title: 'Make a Family page for your All about me book. ',
      picUrl: 'assets/default/default.jpg'
    };

    return stageItem;
  }

}
