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

import * as _ from 'lodash';

import { BaseResizeComponent } from './base-resize.component';




@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.scss']
})
export class PlayComponent extends BaseResizeComponent implements OnInit {
  saveKey = 'ww_matching_cards';
  @ViewChild('canvas', {static: true }) canvas: ElementRef;
  @ViewChild('wrap', {static: true }) wrap: ElementRef;

  // 数据
  data;
  @ViewChild('itemContainer')
  itemContainer: ElementRef;
  cardsArray: Array<{
    pic_id: number,
    word: string
  }>;
  cols = 1;
  rows = 0;
  all = [];

  pairNode = [];

  ANIMATING = false;
  rightAudio = new Audio();
  wrongAudio = new Audio();

  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef) {
    super();
    this.rightAudio.src = 'assets/right.mp3';
    this.rightAudio.load();
    this.wrongAudio.src = 'assets/wrong.mp3';
    this.wrongAudio.load();
  }

  ngOnInit() {
    this.data = {
      contentObj: {
        cards: [{
          pic_id: 'http://staging-teach.cdn.ireadabc.com/8257ac52af8d8201931d08aafe9de685.png',
          word: 'aaaaa'
        }, {
          pic_id: 'http://staging-teach.cdn.ireadabc.com/dae252625e5fc37e992c8e1d4c8f0ad6.png',
          word: 'bbbbbb'
        }]
      }
    };

    // 获取数据
    const getData = ( window as any).courseware.getData;
    getData((data) => {
      console.log('getData', data);
      if (data && typeof data === 'object') {
        this.data = data;
      }
      this.dataChange();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();
      if (window['air']) {
        window['air'].hideAirClassLoading(this.saveKey, this.data);
      }
    }, this.saveKey);
  }
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }
  dataChange() {
    this.cardsArray = _.get(this.data, 'contentObj.cards', []);

    const tmp = [];
    this.cardsArray.map( item => {
      tmp.push({type: 'word', word: item.word});
      tmp.push({type: 'pic', word: item.word, pic_id: item.pic_id});
    });
    this.all = this.shuffle(tmp);
    if (this.all.length <= 2) {
      this.cols = 2;
      this.rows = 1;
    } else if (this.all.length > 2 && this.all.length <= 4) {
      this.cols = 2;
      this.rows = 2;
    } else if (this.all.length > 4 && this.all.length <= 6) {
      this.cols = 3;
      this.rows = 2;
    } else if (this.all.length > 6 && this.all.length <= 8) {
      this.cols = 3;
      this.rows = 3;
    } else if (this.all.length > 8 && this.all.length <= 12) {
      this.cols = 4;
      this.rows = 3;
    } else if (this.all.length > 12 && this.all.length <= 16) {
      this.cols = 4;
      this.rows = 4;
    }
  }

  shuffle(array) {
    array = array.concat();
    let i = 0
      , j = 0
      , temp = null;

    for (i = array.length - 1; i > 0; i -= 1) {
      j = Math.floor(Math.random() * (i + 1));
      temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
    return array;
  }
  toggleCardOpenClose(item) {
    if (!item.opened && item.classList.contains('flip-out')) {
      // console.log('open card', item)
      item.querySelector('.back').style.visibility = 'hidden';
      item.querySelector('.k-full-fill').style.display = 'flex';
      item.querySelector('.k-full-fill').style.visibility = 'visible';
      item.classList.remove('flip-out');
      item.classList.add('flip-in');
      item.opened = 1;
    } else if (item.opened === 1 && item.classList.contains('flip-out')) {
      // console.log('close card', item)
      item.querySelector('.back').style.visibility = 'visible';
      item.querySelector('.k-full-fill').style.display = 'none';
      this.removeNodeFromPair(item);
      item.classList.remove('flip-out');
      item.classList.add('flip-in');
      item.opened = 0;
    } else if (item.classList.contains('flip-in')) {
      // console.log('fliping end', item)
      item.fliping = false;
      // console.log(' ````````````````````', this.pairNode.length);
      if (this.pairNode.length === 2) {
        // console.log('current open two card', item)
        if (this.pairNode[0].word === this.pairNode[1].word &&
          this.pairNode[0].type !== this.pairNode[1].type) {
          const a = this.pairNode[0];
          const b = this.pairNode[1];
          // console.log('card match right', [a, b])
          if (a && b) {
            this.rightAudio.pause();
            this.rightAudio.currentTime = 0;
            setTimeout(() => {
              this.rightAudio.play();
            });
          }

          // console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~', this.pairNode.length)
          setTimeout(() => {
            // try {

            // console.log(123123, [a, b], this.ANIMATING)
            if (a) {
              // console.log('hide a', a);
              // a.style.visibility = 'hidden';
              this.removeNodeFromPair(a , true);
            }
            if (b) {
              // console.log('hide b', b);
              // b.style.visibility = 'hidden';
              this.removeNodeFromPair(b , true);
            }


            // } catch (e) {
            //   debugger
            // }
            // item.style.visibility = 'hidden';
            // console.log('hide', item);
            // this.pairNode = [];
            // item.action = 'close'
            // this.removeNodeFromPair(item, true);
          }, 500);
        } else {
          // console.log('two cards not match', item)

          // console.log(1111, this.pairNode[0].opened, this.pairNode[1].opened )
          if (this.pairNode.length &&  this.pairNode[0].opened && this.pairNode[1].opened) {
            this.wrongAudio.pause();
            this.wrongAudio.currentTime = 0;
            setTimeout(() => {
              this.wrongAudio.play();
            });
            // console.log('close not match cards', item)
            const a = this.pairNode[0];
            const b = this.pairNode[1];
            setTimeout(() => {

              // console.log('wrong close card', a.opened, b.opened, this.pairNode.length);

              if (a.opened) {
                this.doFlipCard(a, 'close');
              }
              if (b.opened) {
                this.doFlipCard(b, 'close');
              }
            }, 500);
          }
          // this.pairNode = [];
          this.removeNodeFromPair(item);
        }
      } else {
        // console.log('card opened not pair', this.ANIMATING, item)
        this.removeNodeFromPair(item);
      }
    }
  }
  removeNodeFromPair(item , force = false   /*item, force?: bool*/) {
    // console.log(item, item.action)
    if (force || item.action === 'close') {
      const idx = this.pairNode.indexOf(item);
      if (idx > -1) {
        this.pairNode.splice(idx, 1);
      }
      if (this.pairNode.length === 0) {
        // console.log('set animating to false')
        this.ANIMATING = false;
      }
    }
  }
  doFlipCard(item, act) {
    item.classList.remove('flip-in', 'flip-out');
    if (!item.hasListener) {
      item.addEventListener('animationend', () => {
        this.toggleCardOpenClose(item);
      }, false);
      item.hasListener = true;
    }
    item.action = act;
    // console.log(act, item.opened, item.classList);
    if (act === 'open' && !item.opened) {
      // item.opened = 1;
      // console.log(item, item.opened);
      item.classList.add('flip-out');
    } else if (act === 'close' && item.opened) {
      // item.opened = 0;

      item.classList.add('flip-out');
    }

  }

  flipCard(evt, type, word) {
    // if (this.MODE !== 'IDLE' && this.MODE !== 'ONE') {
    //   return;
    // }
    if (this.ANIMATING) {
      return;
    }
    this.rightAudio.pause();
    this.rightAudio.currentTime = 0;
    // this.rightAudio.play();
    setTimeout(() => {
      this.rightAudio.play();
    });
    const item = evt.currentTarget;
    if (item.fliping) {
      return;
    }
    if (this.pairNode.length === 2) {
      return;
    }
    item.fliping = true;
    item.type = type;
    item.word = word;
    if (this.pairNode.length === 0) {
      this.pairNode[0] = item;
      // do open card
      this.doFlipCard(item, 'open');
    } else if (this.pairNode.length === 1) {
      if (this.pairNode[0] === item) {
        // close selected card
        this.doFlipCard(item, 'close');
      } else {
        this.pairNode[1] = item;
        // open another card
        this.doFlipCard(item, 'open');
        // this.ANIMATING = true;
      }
    }
  }



}
