import {Component, OnInit} from '@angular/core';
import {File} from '../file';
import {FileService} from '../file.service';

@Component({
  selector: 'app-file',
  templateUrl: './file.component.html',
  styleUrls: ['./file.component.scss']
})
export class FileComponent implements OnInit {

  files: File[];
  // File upload variables
  shortLink = '';
  loading = false; // Flag variable
  fileToUpload: File = null;
  uploadPopupActive = false;

  constructor(private fileService: FileService) {
  }

  ngOnInit(): void {
    this.getFiles();
  }

  getFiles(): void {
    this.fileService.getFiles()
      .subscribe(files => this.files = files);
  }

  onChange(event): void {
    this.fileToUpload = event.target.files[0];
  }

  onUpload(): void {
    this.loading = true;
    console.log(this.fileToUpload);

    this.fileService.upload(this.fileToUpload).subscribe(
      (event: any) => {
        if (typeof (event) === 'object') {
          this.fileToUpload = null;
          (document.getElementById('file-upload-input') as HTMLInputElement).value = '';
          this.shortLink = event.link;
          this.loading = false;
        }
      }
    );
  }

}
