import {Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef} from '@angular/core';
import { getDefaultExercises, getDefaultLetter, getDefaultWord } from '../bean/ExercisesBean';
import { getDefaultTile } from '../bean/TitleBean';



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

  // 储存数据用
  saveKey = "YM5-23";
  // 储存对象
  item;


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

  }


  ngOnInit() {

    this.item = {};

    this.item.skin = 'A';

    this.item.title = getDefaultTile();

    this.item.exercisesArr = [];

    // 获取存储的数据
    (<any> window).courseware.getData((data) => {

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

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

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }



  init() {
    if (!this.item.title) {
      this.item.title = getDefaultTile();
    }

    if (!this.item.exercisesArr) {
      this.item.exercisesArr = [];
    }

    for (let i = this.item.exercisesArr.length; i < 5; ++i) {

      let exercises = getDefaultExercises();

      this.item.exercisesArr.push(exercises);

    }

    for (let i = 0; i < this.item.exercisesArr.length; ++i) {

      let exercises = this.item.exercisesArr[i];

      if (!exercises.wordArr) {
        exercises.wordArr = [];
      }

      let len = exercises.wordArr.length;

      for (let j = len; j < 3; ++j) {

        let word = getDefaultWord();
        exercises.wordArr.push(word);
      }
    }
  }


  /**
   * 储存图片数据
   * @param e
   */
   onImageUploadSuccess(e, item, key) {

    item[key] = e.url;
    this.save();
  }

  /**
   * 储存音频数据
   * @param e
   */
  onAudioUploadSuccess(e, item, key) {

    item[key] = e.url;
    this.save();
  }



  /**
   * 储存数据
   */
  save() {
    (<any> window).courseware.setData(this.item, null, this.saveKey);
    this.refresh();
  }

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }

  saveWord(item) {

    let val = "";

    if (!item.letterArr) {
      item.letterArr = [];
    }

    for (let i = 0; i < item.letterArr.length; ++i) {
      val += item.letterArr[i].val;
    }

    //值发生改变，则重新处理数据
    if (item.val != val) {
      item.letterArr = [];

      for (let i = 0; i < item.val.length; ++i) {
        let letter = getDefaultLetter();
        letter.fontColor = "#363333";
        letter.val = item.val.charAt(i);
        item.letterArr.push(letter);
      }

    }

    this.save();
  }

  clickLetter(letter, i) {

    if (letter.fontColor == "#363333") {
      letter.fontColor = "#c8171e";
    }
    else {
      letter.fontColor = "#363333";
    }

    this.save();
  }
}

