import {
  Component,
  EventEmitter,
  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 = 'hw_007';

  // @Input()
  set item(item) {
    this._item = item;
  }
  get item() {
    return this._item;
  }

  @Output()
  update = new EventEmitter();

  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);
      console.log('~data str:', JSON.stringify(data));
      this.init();

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

      this.refresh();
    }, this.KEY);
  }
  ngOnChanges() {
  }

  ngOnDestroy() {
  }

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

    this.autoPlayBgAudio = !this.item.contentObj.stopPlayBgAudio;
  }

  getDefaultPicArr() {
    return [];
  }

  initData() {
  }

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

    this.save();
  }

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

    this.save();
  }

  onAudioUploadSuccessByItem(e, item, id = null) {

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

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

    this.saveItem();
  }

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

    this.saveItem();
  }

  clickCheckBox() {
    this.item.contentObj.stopPlayBgAudio = !this.autoPlayBgAudio;
    this.saveItem();
  }

  saveItem() {
    this.save();
  }

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

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