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

import { WL01, Rat } from './WL01';
import { JsonPipe } from '@angular/common';

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

export class FormComponent implements OnInit, OnChanges, OnDestroy {


  // 储存数据用
  saveKey = "WL01";
  // 储存对象
  item;


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

  }

  ngOnInit() {

    //this.item = new Course();
    this.item = new WL01();
    this.item.time = 3;
    this.item.mouses = new Array<Rat>();
    // 获取存储的数据
    (<any>window).courseware.getData((data) => {

      if (data) {
        this.item = data;
      }
      //console.log(data);
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);
    //console.log(this.item);
  }

  ngOnChanges() {

  }

  ngOnDestroy() {
  }


  init() {
    if(!this.item){
      this.item = new WL01();
      this.item.time = 3;
      this.item.mouses = new Array<Rat>();
    }
  }



  initData() {
  }



  onImageUploadSuccess(e, item,  key) {
    item[key] = e.url;
    this.save();
  }
  onAudioUploadSuccess(e, item, key) {
    item[key] = e.url;
    this.save();
  }



  saveItem() {
    this.save();
  }

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


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

  addRat(){
    let rat = new Rat();
    if (!this.item.mouses)
      this.item.mouses = new Array<Rat>();
    
    this.item.mouses.push(rat);
    this.save();
  }

  delRat(index){
    if (index !== -1){
      this.item.mouses.splice(index, 1);;
      this.save();
    }
  }


}

