import {Component, EventEmitter, Input, OnChanges, OnDestroy, Output} from '@angular/core';
import { NzMessageService, UploadXHRArgs, UploadFile } from 'ng-zorro-antd';


@Component({
  selector: 'app-upload-image-with-preview',
  templateUrl: './upload-image-with-preview.component.html',
  styleUrls: ['./upload-image-with-preview.component.scss']
})
export class UploadImageWithPreviewComponent implements OnDestroy, OnChanges {
  uploading = false;
  progress = 0;
  @Input()
  picUrl;
  @Input()
  canDelete = false;
  @Output()
  imageUploaded = new EventEmitter();
  @Output()
  imageUploadFailure = new EventEmitter();
  @Output()
  delete = new EventEmitter();
  @Input()
  picItem = null;
  @Input()
  iconSize = 2;
  @Input()
  TIP = 'Click here to upload image';
  @Input()
  disableUpload = false;

  uploadUrl;
  uploadData;

  constructor(private nzMessageService: NzMessageService) {

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

    window['air'].getUploadCallback = (url, data) => {
      this.uploadUrl = url;
      this.uploadData = data;
    };

    this.setUploadUrl();
  }


  setUploadUrl() {

    if (!this.uploadUrl) {

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

      setTimeout(() => {
        this.setUploadUrl();
      }, 500);
    }
  }


  ngOnChanges() {
    if (!this.picItem) {
      return;
    }
  }





  handleChange(info: { type: string, file: UploadFile, event: any }): void {

    console.log('info:' , info);

    switch (info.type) {
      case 'start':
        // this.isUploading = true;
        // this.progress = 0;

        this.picUrl = null;
        // this.beforeUpload(item.file as any);
        if (!this.checkSelectFile(info.file)) {
          return;
        }
        this.uploading = true;
        this.progress = 0;

        break;

      case 'success':
        // this.isUploading = false;
        // this.uploadSuccess(info.file.response);
        // this.audioUploaded.emit(info.file.response);

        this.uploadSuccess(info.file);

        break;
      case 'progress':
        this.progress = parseInt(info.event.percent, 10);
        this.doProgress(this.progress);
        break;
    }
  }

  onDelete() {
    this.delete.emit();
  }
  checkSelectFile(file) {
    const isImg = ['image/jpeg', 'image/png', 'image/jpeg', 'image/gif', 'image/bmp'].includes(file.type);
    if (!isImg) {
      this.nzMessageService.error('You can only upload Image file (jpg|gif|png|bmp)');
      return false;
    }
    const isGif = !['image/jpeg', 'image/png', 'image/jpeg', 'image/bmp'].includes(file.type);
    const delta = isGif ? 20 : 5;
    const isOverSize = file.size / 1024 / 1024 < delta;
    if (!isOverSize) {
      this.nzMessageService.error(`${isGif ? 'Gif' : 'Image'} must smaller than ${delta}MB!`);
      return false;
    }
    return true;
  }

  uploadSuccess = (file) => {
    this.nzMessageService.info('Upload Success');
    this.uploading = false;
    this.picUrl = file.response.url ;
    // this.uploadFinished(url);
    // if (!inOSS) {
    const img = new Image();
    img.addEventListener('load', () => {

      const height = img.naturalHeight;
      const width = img.naturalWidth;
      file['height'] = height;
      file['width'] = width;
      img.remove();
      this.imageUploaded.emit(file.response);
      // this.resService.updateImage(id, {width, height}).then( () => {
      //   this.imageUploaded.emit({res_id: id, id, name, hash, url});
      // });

    });
    img.src = file.response.url;
    // } else {
    //   this.imageUploaded.emit({res_id: id, id, name, hash, url});
    // }
  }

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

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

}
