import {  ApplicationRef, ChangeDetectorRef, Component, ElementRef, ViewChild, OnInit, Input, OnDestroy, HostListener, AfterViewInit } 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 { animate, state, style, transition, trigger } from '@angular/animations';




@Component({
  selector: 'app-play',
  templateUrl: './play.component.html',
  styleUrls: ['./play.component.scss'],
  animations: [
    trigger('dialog', [
      state('fadeIn', style({opacity: '1', top: '61%'})),
      state('moveUp', style({opacity: '1', top: '78%'})),
      transition('* => fadeIn', [
        style({opacity: '0', top: '61%'}),
        animate('1s ease-in-out', style({opacity: '1', top: '61%'}))
      ]),
      transition('* => moveUp', [
        style({opacity: '1', top: '61%'}),
        animate('1s ease-in-out', style({opacity: '1', top: '78%'}))
      ]),
    ])
  ],
})
export class PlayComponent implements OnInit, AfterViewInit, OnDestroy {

  talkText =  {
    A: '',
    B: ''
  };
  _zIdx = 0;
  zIdxB = 0;
  zIdxA = 0;
  // BText: string;
  talkIdx = {
    A: -1,
    B: -1
  };
  talkListData = [];
  audio = new Audio();
  data ;
  @Input() sid ;

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

  animationA = '';
  animationB = '';
  saveKey = 'ww_talk';

  constructor(private appRef: ApplicationRef,
              private changeDetectorRef: ChangeDetectorRef) {

  }
  ngOnInit() {

    this.data = {
      contentObj: {
        talk: [
          [{
            text: 'hello?',
            audio: 0
          }, {
            text: 'fine! thank you. and you?',
            audio: 0
          }],
          [{
            text: 'how are you?',
            audio: 0
          }, {
            text: 'i am fine too',
            audio: 0
          }]
        ]
      }
    };
    // this.init();
    // 获取数据
    const getData = (window as any).courseware.getData;
    getData((data) => {
      if (data && typeof data === 'object') {
        this.data = data;
      }
      this.init();
      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);
  }
  init() {
    this.talkIdx = {
      A: -1,
      B: -1
    };
    this.talkText =  {
      A: '',
      B: ''
    };
    this._zIdx = 0;
    this.zIdxB = 0;
    this.zIdxA = 0;
    this.talkListData = [];
    // this.talkText.A = this.data.contentObj[0][this.talkIdx.A].text;
    // this.talkText.B = this.data.contentObj[1][this.talkIdx.B].text;
    this.talkListBox.nativeElement.querySelector('ul').innerHTML = '';
    // this.addTextToList(this.talkText.A);
    // this.addTextToList(this.talkText.B);
    if (!this.data.contentObj || !this.data.contentObj.talk || !Array.isArray(this.data.contentObj.talk)) {
      return;
    }
    for (let i = 0; i < this.data.contentObj.talk[0].length; i++) {
      this.talkListData.push(this.data.contentObj.talk[0][i]);
      this.talkListData.push(this.data.contentObj.talk[1][i]);
    }
  }
  ngOnDestroy() {
  }


  ngAfterViewInit() {
    // console.log('aaaaaaaaaaaa');
    const el = this.talkListBox.nativeElement;
    const ul = el.querySelector('ul');
    el.addEventListener('mousedown', (e) => {
      if (ul.offsetHeight > el.offsetHeight) {
        el._dragStart = true;
        el._dragStratY = e.pageY;
        el._st = el.scrollTop;
      } else {
        el._dragStart = false;
      }
    });
    el.addEventListener('mousemove', (e) => {
      if (el._dragStart) {
        const delta = el._dragStratY - e.pageY;
        el.scrollTop = el._st + delta;
      }
    });
    el.addEventListener('mouseup', (e) => {
      el._dragStart = false;
    });
    el.addEventListener('mouseout', (e) => {
      el._dragStart = false;
    });
  }


  handleTapText() {
    let group;
    if (this._zIdx % 2 === 0) {
      group = 'A';
    } else {
      group = 'B';
    }
    if (!this.data.contentObj.talk || !Array.isArray(this.data.contentObj.talk)) {
      return;
    }
    if (this.talkIdx[group] !== -1 && this.talkIdx[group] !== 0 &&
      (this.talkIdx[group] % this.data.contentObj.talk[0].length === 0 ||
        this.talkIdx[group] % this.data.contentObj.talk[1].length === 0)) {
      // this.talkIdx[group] = 0;
      return;
    }

    this.talkIdx[group] += 1;
    const g = group === 'A' ? 0 : 1;
    if (!this.data.contentObj.talk[g][this.talkIdx[group]]) {
      return;
    }
    this.talkText[group] = this.data.contentObj.talk[g][this.talkIdx[group]].text;

    this._zIdx ++;
    this['zIdx' + group] = this._zIdx;
    this.addTextToList(this.talkText[group], group);
    if (group === 'A') {
      this.animationA = 'fadeIn';
      this.animationB = 'moveUp';
    } else if (group === 'B') {
      this.animationB = 'fadeIn';
      this.animationA = 'moveUp';
    }
  }
  addTextToList(text: string, group: string) {
    if (!text) {
      return;
    }
    const li = document.createElement('li');
    li.innerHTML = `<img src="assets/talk/${group}.png"
            style="width: 2rem;height: 2rem;
            position: absolute;left: 0px;
            top: 50%;margin-top: -1rem">${text}`;
    // li.style.display = 'inline-flex';
    li.style.wordBreak = 'break-word';
    li.style.lineHeight = '1.5rem';
    li.style.padding = '.25rem .5rem .25rem 2rem';
    li.style.position = 'relative';
    li.style.borderBottom = '1px solid #eee';
    li.style.fontSize = '80%';
    li.style.marginTop = '0.5rem';
    const ul = this.talkListBox.nativeElement.querySelector('ul');
    ul.append(li);
    const p_h = this.talkListBox.nativeElement.offsetHeight;
    const l_h = ul.offsetHeight;
    if ( l_h > p_h ) {
      const ofst = l_h - p_h;
      this.talkListBox.nativeElement.scrollTop = ofst;
    }
  }





}
