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


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {
  // 储存数据用
  saveKey = 'ww_video';
  // 储存对象
  item;
  
  @ViewChild('videoContainer')
  videoContainer: ElementRef;
  @ViewChild('videoNode')
  videoNode: ElementRef;

  newVideoCover = true;

  private tooBigError: NzMessageDataFilled = null;

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

  }


  ngOnInit() {

    this.item = {
      contentObj: {
        pic_id: null,
        video_url: null
      }
    };

    // 获取存储的数据
    (window as any).courseware.getData((data) => {
      if (data) {
        this.item = data;
      }
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();

    }, this.saveKey);

  }


  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  videoLoaded(evt, item) {
    const video  = evt.target;

    if (video.src.startsWith('blob:') && video.videoWidth > 1280 && video.videoHeight > 720) {
      this.tooBigError = this.nzMessageService.error('视频分辨率过大，请调整分辨率后上传，建议 1280x720', {nzDuration: 10 * 1000});
      // video.src = null;
      return ;
    } else {

      if (this.tooBigError && this.tooBigError.messageId) {
        this.nzMessageService.remove(this.tooBigError.messageId);
        this.tooBigError = null;
      }
    }

    if (video.src && video.src.startsWith('blob:')) {
      return;
    }
    if ( item.contentObj.origin_video_url && item.contentObj.origin_video_url.startsWith('http') ) {
      item.video_preview_thumb = null;
      return;
    }
    // item.video_preview_thumb = null;
    this.newVideoCover = true;
    video.currentTime = .1;
  }
  videoError(evt) {
    this.nzMessageService.error('video error');
  }
  videoSeeked(evt) {
    const video  = evt.target;
    if (video.src && video.src.startsWith('blob:')) {
      return;
    }
    if (!this.item.contentObj.pic_id) {
      this.setVideoCover();
      this.newVideoCover = false;
    }
  }

  setVideoCover() {
    if (!this.videoNode) {
      return;
    }
      const video  = this.videoNode.nativeElement;
      if (!video.src) { return; }
      const canvas = document.createElement('canvas');
      canvas.width = video.videoWidth ;
      canvas.height = video.videoHeight ;
      canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);

      const video_preview_thumb = canvas.toDataURL();

      canvas.remove();

    const img = this.convertImageToBlob(video_preview_thumb);
    const formData = new FormData();
    formData.append('file', img);

  }

  convertImageToBlob(data) {
    const imgType = data.substring(data.indexOf(':') + 1, data.indexOf(';'));
    const binary = atob(data.split(',')[1]);
    const array = [];
    let i = 0;
    while (i < binary.length) {
      array.push (binary.charCodeAt(i));
      i++;
    }
    return new Blob([ new Uint8Array(array) ], {type: imgType});
  }

  onVideoUploadSuccess(e) {
    this.item.contentObj.video_url = e.url;
    this.save();
  }

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

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

}

