import { Component, OnDestroy, OnChanges, OnInit, ApplicationRef, ChangeDetectorRef, ViewChild, ElementRef } from '@angular/core';
import { ComponentBase } from './ComponentBase';
import { MetaFormCreator } from './mataFormCreator';
import {NzMessageService, NzMessageDataFilled} from 'ng-zorro-antd';
import {HttpClient, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http';

let replaceAll = function (str, s1, s2) {
  return str.replace(new RegExp(s1, "gm"), s2);
}
@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent extends ComponentBase implements OnInit, OnChanges, OnDestroy {
  // 储存数据用
  saveKey = "cartoon_video";

  @ViewChild('videoContainer')
  videoContainer: ElementRef;
  @ViewChild('videoNode')
  videoNode: ElementRef;

  newVideoCover = true;

  private tooBigError: NzMessageDataFilled = null;


  uploadUrl;
  uploadData;


  item = {
    video_url: "",
  };

  constructor(public nzMessageService: NzMessageService,  private http: HttpClient, public appRef: ApplicationRef, public changeDetectorRef: ChangeDetectorRef) {
    super(appRef, changeDetectorRef);
    this.uploadUrl = (<any> window).courseware.uploadUrl();
  }
  init(): void {
  }

  ngChange(i, j) {
    this.save();
  }

  onVideoUploaded(evt) {
    this.item.video_url = evt.url;
    console.log(evt);
    this.save();
  }

  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.origin_video_url && item.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) {
    return;
  }

  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();
    const ext = img.type.replace('image/', '');
    formData.append('file', img, `cover.${ext}`);

    this.http.post(this.uploadUrl, formData).subscribe(
      (res: any) => {
        (window as any).courseware.sendEvent("screenshot", {"url": res.url}, this.saveKey);
      },
      (err) => {
        console.log(err);
        this.nzMessageService.error('封面截取失败');
      }
    );
  }

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

}