import { AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-hensel-drag-n-drop',
  templateUrl: './hensel-drag-n-drop.component.html',
  styleUrls: ['./hensel-drag-n-drop.component.scss']
})
export class HenselDragNDropComponent implements OnInit {

  @Input() accept: string = '.jpg,.png';
  @Input() multiple: boolean = true;
  @Input() caption: string;
  @Input() captionClass: string = '';
  @Input() buttonText: string;
  @Input() icon: string = 'cloud_upload';
  @Input() iconSizePrc: number = 1;
  @Input() onFileUpload: (any) => void;
  @Input() title: string;
  @Input() button: string = '';
  @Input() disabled: boolean = false;
  @Input() uploadAsBase64: boolean = false;
  @Input() onStartingUpload: (any) => void;
  @Input() onStartingUploadAsync: () => Promise<void>;
  @Input() onFinishUpload: () => void;
  @ViewChild('fileInput') fileInput: ElementRef;

  public fontSize: string = '100%';


  constructor() {
    this.readMultipleFiles = this.readMultipleFiles.bind(this);
    this.startUpload = this.startUpload.bind(this);
  }

  ngOnInit() {
  }

  selectFiles() {
    if (!this.disabled) this.fileInput.nativeElement.click();
  }

  private uploadFile(file: File, indx: number, lastIndx: number) {
    if (file) {
      if (this.uploadAsBase64) {
        const fr = new FileReader(); // FileReader instance
        fr.onload = () => {
          const fileBase64: string = fr.result.toString();
          if (this.onFileUpload) this.onFileUpload({ fileBase64: fileBase64, filename: file.name, index: indx, lastIndex: lastIndx });
          /*
                    const img = new Image();
                    img.src = fileBase64;
                    img.onload = () => {
                      this.catalogDataService.newImage({ name: file.name, image: fileBase64.split(',')[1] }, img.width, img.height, indx, this.imageGrid);
                    };
          */
        };
        fr.readAsDataURL(file); //Read file as Binary
      } else if (this.onFileUpload) this.onFileUpload(file);
    } else {
      alert('File not selected or browser incompatible!');
    }
  }


  public async startUpload(files: FileList) {
    const _files: FileList = { length: files.length, item: null };
    Object.assign(_files, files); //must save clone of files, bcs orig get lost
    if (this.onStartingUploadAsync) await this.onStartingUploadAsync();
    // this.readMultipleFiles(_files);
    if (!this.onStartingUpload) this.readMultipleFiles(_files);
    else {
      const noOfFiles = _files.length;
      for (let inx = 0; inx < noOfFiles; inx++) {
        if (this.validExtension(_files[inx].name)) {
          this.onStartingUpload(() => this.readMultipleFiles(_files));
          return;
        }
      }
    }
  }


  public readMultipleFiles(files: FileList) {
    const noOfFiles = files.length;
    let startInx: number = 0;
    for (let inx = 0; inx < noOfFiles; inx++) {
      if (!this.validExtension(files[inx].name)) continue;
      // if (startInx === 0 && this.onStartingUpload) this.onStartingUpload();
      this.uploadFile(files[inx], startInx, noOfFiles - 1);
      if (!this.multiple) break;
      startInx++;
    }
    if (this.onFinishUpload) this.onFinishUpload();
  }

  validExtension(name: string) {
    if (!this.accept) return true;
    let exts: string;
    if (this.accept.toLowerCase() === 'image/*') exts = ',.jpg,.jpeg,.png,.tiff,.bmp,';
    else exts = ',' + this.accept.replace(' ', '').toLocaleLowerCase() + ',';
    const re: RegExp = /(?:\.([^.]+))?$/;
    const ext = re.exec(name)[1].toLocaleLowerCase();
    return exts.indexOf(',.' + ext + ',') !== -1;
  }


  calcFontSize(width: number, height: number) {
    return ((Math.min(width, height) - 4) / 12 * 100 * this.iconSizePrc).toFixed() + '%';

  }
}
