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 {

  constructor(private fileService: FileService) { }
  files: File[];

  // File upload variables
  shortLink: string = ""; 
  loading: boolean = false; // Flag variable 
  fileToUpload: File = null;

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

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

  onClick(): void {
    var modal = document.getElementById("myModal");
    modal.style.display = "block";
  }

  onClick2(): void {
    var modal = document.getElementById("myModal");
    modal.style.display = "none";
    this.shortLink = "";
    this.loading = false;
  }

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

  onUpload() { 
    this.loading = !this.loading; 
    console.log(this.fileToUpload); 

    this.fileService.upload(this.fileToUpload).subscribe( 
      (event: any) => { 
        if (typeof (event) === 'object') { 

          this.shortLink = event.link; 
          this.loading = false; 
        } 
      } 
    ); 
  } 

}
