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

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})

export class FormComponent implements OnInit, OnChanges, OnDestroy {

  dataArray = []; 
  _item: any; 
  KEY = 'ZD04';

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

  @Output()
  update = new EventEmitter();
  constructor(private appRef: ApplicationRef) {

  }

  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 = {};
      }
      this.init();
      this.refresh();
      this.saveItem();
    }, this.KEY);
  }
  ngOnChanges() {

  }

  ngOnDestroy() {
  }


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

  cardItemData(){
    return {
      time: 5,
        question:{
          text:"",
          audio_url:""
        },
    };
  }

  cardChoiceData(){
    return { isText: true, text: "", image_url: "" }
  }

  getDefaultPicArr() {
    let arr = []; 
    return arr;
  }


  initData() {
  }

  deleteItem(index) { 
    if (index !== -1) {
      this.dataArray.splice(index, 1);
    }
    this.save();
  }
 
  deleteChoice(questionIndex, choiceIndex){
    if (questionIndex !== -1 && choiceIndex !== -1) {
      this.dataArray[questionIndex].choice.incorrect.splice(choiceIndex, 1);
    }
    this.save();
  }
  addChoice(questionIndex) { 
    let item = this.cardChoiceData();  
    this.dataArray[questionIndex].choice.incorrect.push(item);
    this.saveItem();
  }

  onImageUploadSuccessByItem(e, item) {
    item.image_url = e.url
    this.save(); 
  }
 
  onAudioUploadSuccessByItem(e, item) { 
    item.audio_url = e.url; 
    this.save();
  }
  onTitleAudioUploadSuccess(e) { 
    this.item.contentObj.titleAudio_url = e.url;
    this.save();
  }
  addItem() { 
    let item = this.cardItemData();  
    this.dataArray.push(item);
    this.saveItem();
  }

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

    this.saveItem();
  }

  clickCheckBox() {
    this.saveItem();
  }


  saveItem() {
    this.save();
  }

  save() {
    (<any> window).courseware.setData(this.item, null, this.KEY);
    this.refresh();
    //console.log(this.item)
    console.log('this.item = ' + JSON.stringify(this.item));
  }

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

}

