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

import {
  removeItemFromArr, ShapeRect, tweenChange,

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

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

import TWEEN from '@tweenjs/tween.js';
import { Title } from './Title';
import { Listening } from './Listening';
import { Letter } from './Letter';
import { Exercises } from './Exercises.spreat';
import { getDefaultExercises } from '../bean/Exercises';
import { getDefaultTile } from '../bean/TitleBean';
import { exception } from 'console';




@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 = 'YM5-15';

  canTouch = true;

  /**标题*/
  title: Title;

  curAudio;

  exercisesArr: Array<Exercises> = [];

  oldPos;

  itemOldPos;

  lastClickTime: Date;

  curListening: Listening;

  listening: Listening;

  listeningArr: Array<Listening> = [];

  @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;
      }
      else {
        let defaultData = '{"title":{"part1":"C","part2":"Read and point"},"letterArr":[{"key":"K-1612945850419","isFill":"0","val":"-dis"},{"key":"K-1612945972128","isFill":"0","val":"-aw-"},{"key":"K-1612947526926","isFill":"0","val":"ph"},{"key":"K-1612947527364","isFill":"0","val":"-aw-"},{"key":"K-1612947541415","isFill":"0","val":"-ch"},{"key":"K-1612947545454","isFill":"0","val":"-ed"},{"key":"K-1612947548919","isFill":"0","val":"pre-"}],"exercisesArr":[{"letterArr":[{"key":"K-1613141016560","isFill":"0","val":"Hello,My name is chenjp.Hello My n"},{"key":"K-1613141016560","isFill":"1","val":"_"},{"key":"K-1613141016560","isFill":"0","val":"e is chenjp.Hello,"}],"key":"K-1612947526926","answer":{"letterArr":[{"key":"","isFill":"0","val":"name"},{"key":"K-1612705253202","isFill":"1","val":"pah","val2":"pah"}]},"index":1,"val":"Hello,My name is chenjp.Hello My n_e is chenjp.Hello,","audioUrl":"http://staging-teach.cdn.ireadabc.com/8970ccce02d3a37640c80e02626fefb8.mp3"},{"key":"K-1612945850419","answer":{},"index":2,"val":"I _agree with my dad about it.","letterArr":[{"key":"K-1612946396917","isFill":"0","val":"I "},{"key":"K-1612945850419","isFill":"1","val":"dis"},{"key":"K-1612946396917","isFill":"0","val":"agree with my dad about it."}],"audioUrl":"http://staging-teach.cdn.ireadabc.com/ef597f87e534ab2c73f4f9ed34eb26fa.mp3"},{"key":"K-1612947545454","answer":{},"index":3,"val":"He received the best treat_ for a cold yesterday.","letterArr":[{"key":"K-1613141079966","isFill":"0","val":"He received the best treat"},{"key":"K-1613141079966","isFill":"1","val":"_"},{"key":"K-1613141079966","isFill":"0","val":" for a cold yesterday."}],"audioUrl":"http://staging-teach.cdn.ireadabc.com/55addbbc6a4da4a63bc22988063bdded.mp3"},{"key":"K-1612947541415","answer":{},"index":4,"val":"He received the best treat_ for a cold yesterday.","letterArr":[{"key":"K-1613141080944","isFill":"0","val":"He received the best treat"},{"key":"K-1612947541415","isFill":"1","val":"ch"},{"key":"K-1613141080944","isFill":"0","val":" for a cold yesterday."}],"audioUrl":"http://staging-teach.cdn.ireadabc.com/71eb8fcc0895873363840db7bc0c5883.mp3"}]}';
        this.data = JSON.parse(defaultData);
      }
      //console.log('data:', JSON.stringify(data));

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

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

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

    }, this.saveKey);

  }

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


  cleanAudio() {
    if (this.audioObj) {
      for (const key in this.audioObj) {
        this.audioObj[key].pause();
      }
    }
  }


  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;
    window['curImages'] = this.images;
  }






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

    return audio;
  }



  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(a);
      };
      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.title) {
      this.data.title = getDefaultTile();
    }

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


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


  }

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


    this.rawAudios.forEach((item, key) => {
      // 音效
      this.addUrlToAudioObj(key, item);
    })



    //标题发音
    if (this.data.title.audioUrl) {
      this.addUrlToAudioObj('titleAudio', this.data.title.audioUrl);
    }


    //听力材料
    if (this.data.audioUrl) {
      this.addUrlToAudioObj('listenAudio', this.data.audioUrl);
    }


    //练习题音效
    for (let i = 0; i < this.data.exercisesArr.length; ++i) {

      let exercises = this.data.exercisesArr[i];

      if (exercises.answer && exercises.audioUrl) {
        this.addUrlToAudioObj(exercises.audioUrl);
      }
    }

  }



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

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


    this.renderArr = [];

    if (this.curAudio) {
      this.curAudio.pause();
    }

    this.curAudio = null;

    this.exercisesArr = [];

    this.listeningArr = [];
  }



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

    this.initTitle();

    this.initBottomPart();

    this.initExercises();
  }


  initTitle() {

    const title = new Title(this.data.title, this.images);

    title.init(this.mapScale, this.mapScale);
    title.audio = this.audioObj['titleAudio'];
    this.title = title;

    title.titleBg.y = 0;
    title.titleBg.x = 0;

    this.renderArr.push(title.titleBg);
  }

  initBottomPart() {

    if (!this.data.audioUrl) {
      return;
    }
    const listening = new Listening(this.audioObj['listenAudio'], this.images);
    listening.init(this.mapScale, this.mapScale);

    listening.bg.x = this.canvasWidth - listening.bg.width - 10 * this.mapScale;
    listening.bg.y = this.canvasHeight - listening.bg.height - 8 * this.mapScale;
    this.listening = listening;

    this.renderArr.push(listening.bg);
  }


  private initExercises() {

    const getView = (item, index) => {

      let exercises = new Exercises();

      exercises.index = index;

      exercises.init(this.images, this.data.backgroudColor, item, this.mapScale, this.mapScale);

      return exercises;
    }

    let exercisesArr = this.data.exercisesArr;

    let col = 1;

    let row = Math.ceil(exercisesArr.length / col);

    let dW = 0 * this.mapScale;

    let dH = 35 * this.mapScale;

    let w = 1280 * this.mapScale;

    let h = 0 * this.mapScale;

    let totalWidth = col * w + (col - 1) * dW;

    let totalHeight = row * h + (row - 1) * dH;

    let startX = (this.canvasWidth - totalWidth) / 2;

    for (let i = 0; i < exercisesArr.length; ++i) {


      let exercises = getView(exercisesArr[i], i + 1);

      totalHeight += exercises.bg.height;

      this.renderArr.push(exercises.bg);

      this.exercisesArr.push(exercises);
    }


    let startY = this.canvasHeight / 2 - 254 * this.mapScale;

    let tempY = startY;

    for (let i = 0; i < this.exercisesArr.length; ++i) {

      let exercises = this.exercisesArr[i];

      exercises.bg.x = startX;

      exercises.bg.y = startY;

      //换行
      if ((i + 1) % row != 0) {

        startY += dH + exercises.bg.height;
      }
      else {
        startX += dW + w;
        startY = tempY;
      }
    }
  }



  mapDown(event) {

    if (!this.canTouch) {
      return;
    }


    if (this.curAudio) {
      if (!this.listening || this.curAudio != this.listening.audio) {
        this.curAudio.pause();
      }
    }

    if (this.listening && this.checkClickTarget(this.listening.bg)) {

      this.curAudio = this.listening.play(() => {
        this.listening.reset();
      });

      return;
    }

    if (this.curAudio) {
      if (this.listening && this.curAudio == this.listening.audio) {
        this.listening.pauseAudio();
      }
      else {
        this.curAudio.pause();
      }

    }

    if (this.checkClickTarget(this.title.titleBg)) {
      this.curAudio = this.title.playAudio();
      return;
    }

    this.oldPos = { x: this.mx, y: this.my };

    let clicked = false;

    if (clicked) {
      this.itemOldPos = { x: this.mx, y: this.my };
      return;
    }


    let listening;

    for (let i = 0; i < this.listeningArr.length; ++i) {

      listening = this.listeningArr[i];

      if (this.checkClickTarget(listening.bg)) {
        clicked = true;
        break;
      }

    }

    if (clicked) {
      if (listening == this.curListening) {

        if (listening.playing) {
          listening.pauseAudio();
        }
        else {
          this.curAudio = listening.play(() => {
            listening.reset();
          });
        }
      }
      else {

        if (this.curListening) {
          this.curListening.pauseAudio();
        }

        this.curListening = listening;

        this.curAudio = listening.play(() => {
          listening.reset();
        });

      }
    }
  }

  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);

  }


  private clickExercies(curExer) {
    if (!curExer) {
      return;
    }

    if (curExer.answered) {
      if (this.checkClickTarget(curExer.answer)) {
        this.playAudio(curExer.data.audioUrl, true);
      }
      return;
    }
  }

  
}
