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




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

  // 数据
  data;
  saveKey = 'picture-group';
  result: object[][];


  @ViewChild('itemsContainer')
  itemsContainer: ElementRef;
  CURRENT_ITEM = null;
  CURRENT_ITEM_EL = null;
  CURRENT_ITEM_GROUP = -1;
  _WIDTH = '';
  _HEIGHT = '';
  rightAudio = new Audio();
  wrongAudio = new Audio();
  options: any[];

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

  ngOnInit() {
    this.data = {
      contentObj: {
        groups: [
          {name: 'aaaa', options: [
            {showText: true, text: "11111"},
            {showText: true, text: "22222"}
          ]},
          {name: 'bbbb', options: [
            {showPic: true, pic_id: "assets/picture-group/2.png"},
            {showPic: true, pic_id: "assets/picture-group/3.png"},
            {showPic: true, pic_id: "assets/picture-group/4.png"}
          ]}
        ]
      }
    };

    // 获取数据
    const getData = ( window as any).courseware.getData;
    getData((data) => {
      if (data && typeof data === 'object') {
        this.data = data;
      }
      this.init();
      window["air"].hideAirClassLoading(this.saveKey, this.data);

      this.refresh();
    }, this.saveKey);
  }

  init(){
    this.result = [[], []];
    let item_length = 0;
    const groups = _.get(this.data.contentObj, 'groups', []);
    if (groups.length === 0) {
      this.data.contentObj.groups = [];
    }

    const [group0, group1] = this.data.contentObj.groups;
    if (group0.options) {
      this.options = [...group0.options];
      this.options.forEach((i) => (i.gIndex = 0));
    }
    if (group1.options) {
      this.options = [...this.options, ...group1.options];
      this.options.forEach((i) => {
        if (i.gIndex === undefined) {
          i.gIndex = 1;
        }
      });
    }
    this.options.sort(() => {
      return 0.5 - Math.random();
    });

    for (const group of groups) {
      item_length += group.options.length;
    }
    this._HEIGHT = item_length > 4 ? '29.5%' : '35.5%';
    this._WIDTH = item_length > 4 ? '20%' : '25%';
  }

  selectItem(item, evt) {

    const el = evt.currentTarget.parentNode;
    this.CURRENT_ITEM = item;
    this.CURRENT_ITEM_EL = el;
    this.CURRENT_ITEM_GROUP = item.gIndex;
    if (el.classList.contains('selected')) {
      // if (this.result[this.CURRENT_GROUP_INDEX].length === 5
      //   /* this.data.contentObj.groups[this.CURRENT_GROUP_INDEX].options.length */
      // ) {
      //   return;
      // }
      // el.classList.remove('selected');
      // el.style.visibility = 'hidden';
    } else {
      const els = this.itemsContainer.nativeElement.querySelectorAll('.item-box');
      els.forEach((n) => {
        n.classList.remove('selected');
        n.classList.remove('tada');
        n.classList.remove('infinite');
        n.classList.remove('animated');
      });
      el.classList.add('selected');
    }
  }

  selectGroup(gIdx, evt) {
    if (!this.CURRENT_ITEM ||
      !this.CURRENT_ITEM_EL ||
      this.CURRENT_ITEM_GROUP < 0) {
      return;
    }
    if (this.result[gIdx].length >= 5
    ) {
      return;
    }
    if (this.CURRENT_ITEM_GROUP === gIdx) {
      this.rightAudio.pause();
      this.rightAudio.currentTime = 0;
      const rightPromise = this.rightAudio.play();
      if (rightPromise !== undefined) {
        rightPromise.then(function () {
        }).catch(function (error) {
          this.rightAudio.play();
        });
      }

      this.CURRENT_ITEM_EL.classList.remove('selected');
      this.CURRENT_ITEM_EL.classList.remove('tada');
      this.CURRENT_ITEM_EL.classList.remove('infinite');
      this.CURRENT_ITEM_EL.classList.remove('animated');
      this.CURRENT_ITEM_EL.style.visibility = 'hidden';
      this.result[gIdx].push(this.CURRENT_ITEM);
      this.CURRENT_ITEM = null;
      this.CURRENT_ITEM_EL = null;
      this.CURRENT_ITEM_GROUP = -1;

    } else {
      this.wrongAudio.pause();
      this.wrongAudio.currentTime = 0;
      const rightPromise = this.wrongAudio.play();
      if (rightPromise !== undefined) {
        rightPromise.then(function () {
        }).catch(function (error) {
          this.wrongAudio.play();
        });
      }
      this.CURRENT_ITEM_EL.classList.remove('selected');
      this.CURRENT_ITEM_EL.classList.add('tada');
      this.CURRENT_ITEM_EL.classList.add('infinite');
      this.CURRENT_ITEM_EL.classList.add('animated');
    }
  }

  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }


}
