import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnChanges,
  OnInit,
  Output,
  ApplicationRef,
  ChangeDetectorRef
} from '@angular/core';



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

  picArr = [];

  _item: any;


  KEY = 'dfzx_16';


  letter = '';
  soundArr;




  // @Input()
  set item(item) {
    this._item = item;
    // this.init();

  }
  get item() {
    return this._item;
  }

  @Output()
  update = new EventEmitter();


  bgItem;
  hotZoneItemArr;




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

  }


  ngOnInit() {

    this.item = {};
    this.item.contentObj = {};

    const getData = (<any> window).courseware.getData;
    getData((data) => {

      if (data) {
        this.item = data;
      } else {
        this.item = {};
      }

      if ( !this.item.contentObj ) {
        this.item.contentObj = {};
      }

      console.log('~data:', data);
      this.init();

      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();

      this.refresh();

    }, this.KEY);

    // this.initData();
  }
  ngOnChanges() {

  }

  ngOnDestroy() {
  }


  init() {

    if (this.item.contentObj.picArr) {
      this.picArr = this.item.contentObj.picArr;
    } else {
      this.picArr = this.getDefaultPicArr();
      this.item.contentObj.picArr = this.picArr;
    }

    this.bgItem = this.item.contentObj.bgItem || {};
    this.hotZoneItemArr = this.item.contentObj.hotZoneItemArr || [];
    this.letter = this.item.contentObj.letter || '';



    console.log('item:' , this.item);
    // this.picArr = this.getDefaultPicArr();
    // this.item.contentObj.picArr = this.picArr;
    // console.log('this.item:;', this.picArr);

  }

  getDefaultPicArr() {
    const arr = [];

    return arr;
  }


  changeOptions(data) {
    console.log('data: ', data);
    this.save();
  }



  getOptions() {

    const options = [];
    const arr = this.hotZoneItemArr;
    for (let i = 0; i < arr.length; i++) {
      const data = {};
      data['key'] = arr[i]['key'];
      data['index'] = arr[i]['index'];
      data['label'] = 'item-' + (arr[i]['index'] + 1);
      data['value'] = arr[i]['index'];


      options.push(data);
    }

    return options;
  }

  refreshOptions() {

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

      picArr[i].options = this.getOptions();

    }
  }


  deleteItem(data, arr = null) {
    if (!arr) {
      arr = this.picArr;
    }
    const index = arr.indexOf(data);
    if (index !== -1) {
      arr.splice(index, 1);
    }

    // this.update.emit(this.item);
    // this.refreshOptions();
    this.save();
  }

  letterChange(e) {

    const value = e.data;

    if (value) {

      console.log('in letterChange e:', value);

      if (/^[A-Za-z]+$/.test( value )) {
        console.log('aaa');
        this.letter = value;
      } else {
        console.log('bbb');
        this.letter = '';
      }

    }

  }






  onImageUploadSuccessByItem(e, item, id = null) {

    if (id != null) {
      item[id + '_pic_url'] = e.url;
    } else {
      item.pic_url = e.url;
    }

    this.save();
    // this.update.emit(this.item);

    // console.log('this.item: ', this.item);
  }




  onAudioUploadSuccessByItem(e, item, id = null) {

    if (id != null) {
      item[id + '_audio_url'] = e.url;
    } else {
      item.audio_url = e.url;
    }
    // this.update.emit(this.item);
    this.save();
  }



  addPic() {
    this.picArr.push({
      pic_url: '',
      audio_url: '',
      text: '',
      options: this.getOptions()
      // text: '',
      // radioValue: 'A'
    });

    // this.refreshOptions();

    this.saveItem();
  }

  radioClick(it, radioValue) {
    it.radioValue = radioValue;

    this.saveItem();
  }

  clickCheckBox() {
    console.log(' in clickCheckBox');
    this.saveItem();
  }


  saveItem() {
    // this.update.emit(this.item);

    this.item.contentObj.letter = this.letter;
    this.save();
  }


  setHotZoneOldData(oldArr, newArr) {
    for (let i = 0; i < newArr.length; i++) {

      const newData = newArr[i];
      for (let j = 0; j < oldArr.length; j++) {

        const oldData = oldArr[j];
        if (newData.key == oldData.key) {
          newData.audio_url = oldData.audio_url;
        }
      }
    }
  }

  saveData(e) {
    console.log('savedata e:', e);


    this.bgItem = e.bgItem;

    this.setHotZoneOldData(this.hotZoneItemArr, e.hotZoneItemArr);

    this.hotZoneItemArr = e.hotZoneItemArr;

    this.item.contentObj.bgItem = this.bgItem;
    this.item.contentObj.hotZoneItemArr = this.hotZoneItemArr;

    this.refreshOptions();
    this.save();
  }


  save() {
    (<any> window).courseware.setData(this.item, null, this.KEY);
    this.refresh();
  }

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

}

