import {Component, ElementRef, EventEmitter, Input, OnChanges, OnDestroy, Output, SecurityContext, ViewChild} from '@angular/core';
import {NzMessageService, UploadChangeParam, UploadFile, UploadFileStatus} from 'ng-zorro-antd';
import {DomSanitizer, SafeResourceUrl} from '@angular/platform-browser';


@Component({
  selector: 'app-upload-video',
  templateUrl: './upload-video.component.html',
  styleUrls: ['./upload-video.component.scss']
})
export class UploadVideoComponent implements OnChanges, OnDestroy {
  uploading = false;
  checking = false;
  checkVideoExists = false;
  uploadClicked = false;

  @Input()
  videoFile = null;
  uploaderInst = null;

  progress = 0;
  // @Input()
  // setCovering = false;

  @Input()
  videoUrl = '';
  @ViewChild('videoNode', {static: true })
  videoNode: ElementRef;




  // @Input()
  // extractCoverFunc = null;

  @Output()
  videoUploaded = new EventEmitter();
  @Output()
  videoUploadFailure = new EventEmitter();
  @Output()
  extractVideoCover = new EventEmitter();


  @Input()
  showUploadBtn = true;
  @Input()
  item: any;
  // videoItem = null;

  uploadUrl;
  uploadData;

  constructor(private nzMessageService: NzMessageService,
              private sanitization: DomSanitizer
              // private cwService: _coursewareService,
              // private resService: ResourceService
              ) {
    this.uploading = false;
    this.videoFile = null;


    this.uploadUrl = (<any> window).courseware.uploadUrl();
    this.uploadData = (<any> window).courseware.uploadData();

    window['air'].getUploadCallback = (url, data) => {

      this.uploadUrl = url;
      this.uploadData = data;
    };

  }
  ngOnChanges() {
    // if (!this.videoFile || this.showUploadBtn) {
    //   return;
    // }
    // this.beforeUpload(this.videoFile);
    // this.handleUpload();
  }
  ngOnDestroy(): void {
    URL.revokeObjectURL(this.videoUrl);
  }

  httpHeadCall(requsetUrl: string, callback) {
    let xhr = new XMLHttpRequest();
    console.log("Status: Send Post Request to " + requsetUrl);
    try {
      xhr.onreadystatechange = () => {
        try {
          console.log('xhr.readyState: ', xhr.readyState);
          if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 400)) {
              callback(true);
            } else {
              callback(false);
            }
          }

        } catch (e) {
          console.log(e)
        }
      };
      xhr.open("HEAD", requsetUrl, true);
      xhr.send();
      xhr.timeout = 15000;
      xhr.onerror = (e) => {
        callback(false);
      };
      xhr.ontimeout = (e) => {
        callback(false);
      };
    } catch (e) {
      console.log("Send Get Request error: ", e)
    }
  }

  safeVideoUrl(url) {
    const _url = url.replace("_l.", ".");
    return this.sanitization.bypassSecurityTrustResourceUrl(_url); // `${url}`;
  }
  videoLoadedMetaData() {

  }


  handleChange(info: UploadChangeParam): void {
    switch (info.type) {
      case 'start':
        if (!this.checkSelectFile(info.file)) {
          return;
        }
        this.uploading = true;
        this.progress = 0;
        break;
      case 'success':
        let url = info.file.response.url;
        url = url.substring(0, url.lastIndexOf(".")) + "_l.mp4";
        info.file.response.url = url;
        this.uploadSuccess(info.file);
        break;
      case 'progress':
        this.progress = info.event.percent;
        this.doProgress(this.progress);
        break;
    }
  }

  checkSelectFile(file) {
    if (!file.lastModified) {
      return false;
    }
    const delta = 500;
    const isOverSize = (file.size / 1024 / 1024) < delta;
    if (!isOverSize) {
      this.nzMessageService.error(`video must smaller than ${delta}MB!`);
      return false;
    }
    return true;
  }
  checkHashFinish = (hash) => {
    this.checking = false;
    this.uploading = true;
  }

  uploadSuccess = (file) => {

    this.nzMessageService.info('Upload Success');
    // this.updateStatus(false);
    this.uploading = false;
    this.videoFile = null;
    // this.updateSource(url);
    this.videoUrl = file.response.url;
    // console.log(this.picUrl)
    // this.uploadFinished(url);
    // if (!inOSS) {
      const vid = document.createElement('video');
      vid.addEventListener('loadedmetadata', () => {
        const height = vid.videoHeight;
        const width = vid.videoWidth;
        let duration = vid.duration;
        if (duration) {
          duration = duration * 1000;
        }
        file.height = height;
        file.width = width;
        file.duration = duration;
        vid.preload = 'none';
        vid.src = '';
        vid.remove();

        this.videoUploaded.emit(file.response);

        // this.resService.updateVideo(id, {width, height, duration}).then( () => {
        //   this.videoUploaded.emit({res_id: id, id, name, hash, url});
        // });

      });
      vid.src = file.response.url;
    // } else {
    //   this.videoUploaded.emit(file.response);
    // }



  }



  uploadFailure = (err, file) => {
    this.uploading = false;
    if (err.name && err.name === 'cancel') {
      return;
    }
    console.log(err);
    this.nzMessageService.error('Upload Error ' + err.message);
    this.videoUploadFailure.emit(file);
  }

  doProgress =  (p) => {
    if (p > 1) {
      p = 1;
    }
    if (p < 0) {
      p = 0;
    }
    // console.log(Math.floor(p * 100));
    this.progress =  Math.floor(p * 100);
  }
}

