import { Observable, Subject } from 'rxjs';
import { share } from 'rxjs/operators';

export class FileUploadItem {
  file: File;
  uploadTime: number;
  uploadingProgress$: Observable<number>;

  private uploadingProgress: Subject<number>;
  private uploadStartTime: number;

  private constructor(file: File) {
    this.file = file;
  }

  static fromFiles(files: FileList): FileUploadItem[] {
    const fileItems: FileUploadItem[] = [];

    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < files.length; i++) {
      fileItems.push(new FileUploadItem(files[i]));
    }

    return fileItems;
  }

  uploadStart(): Subject<number> {
    this.uploadStartTime = new Date().getTime();
    this.uploadingProgress = new Subject<number>();
    this.uploadingProgress$ = this.uploadingProgress
      .asObservable()
      .pipe(share());
    return this.uploadingProgress;
  }

  uploadComplete() {
    const endTime = new Date().getTime();
    this.uploadTime = endTime - this.uploadStartTime;
    this.uploadingProgress.complete();
  }
}
