import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef, ViewChild, ElementRef} from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';



@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
  // @Input()
  item;
  @ViewChild('videoContainer')
  videoContainer: ElementRef;
  @ViewChild('videoNode')
  videoNode: ElementRef;
  @Output()
  update = new EventEmitter();

  intervalId;

  picArr;

  side

  saveKey = 'ssy003'; 



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


  }


  ngOnChanges() {

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

      if (data) {
        this.item = data;
      } else {
        this.item = {};
        this.item.contentObj = {};
        this.item.sideA=1;
     
      }
      if(this.item.sideA==1){
        this.side='B';
      }
      else if(this.item.sideB==1){
        this.side='A';
      }


      this.initDefaultData();


      console.log('data:', data);

      this.init();

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

      this.refresh();

    }, this.saveKey);



  }

  sidec(){
    if(this.side=="A"){
      this.item.sideA=0;
      this.item.sideB=1;
     
    
    }
    if(this.side=="B"){
      this.item.sideA=1;
      this.item.sideB=0;
    }
    this.save();
  }

  initDefaultData() {

    
    const picArr = this.item.contentObj.picArr;
    if (!picArr) {

      const picArr = [];
      for (let i = 0; i < 6; i ++) {
        picArr.push({
          pic_url: '',
          audio_url: '',
          title:'',
          sideA:'',
          sideB:''
        });
      }

      this.item.contentObj.picArr = picArr;
    }
  }



  ngOnDestroy() {
    console.log('in ngOnDestory');
  }

  init() {

    this.picArr = this.item.contentObj.picArr || [];

    this.item.contentObj.picArr = this.picArr;

  }






  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();
  }



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

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


