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

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

  user: User;
  files: File[];
  shortLink = '';
  loading = false; // Flag variable
  deleting = false; //Flag variable
  fileToUpload: File = null;
  uploadPopupActive = false;

  constructor(private fileService: FileService,
    private dataService: ApiService ) {
  }

  ngOnInit(): void {
    this.user = JSON.parse(this.dataService.getToken());
    this.getFiles();
  }

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

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

  onUpload(): void {

    if ((document.getElementById('file-upload-input') as HTMLInputElement).value === '') {return; }

    this.loading = true;
    console.log(this.fileToUpload);

    this.fileService.upload2(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;
        }
      }
    );
  }

  onDelete(file): void {
    this.deleting = true;
    this.fileService.delete(file).subscribe(
      () => {
        this.deleting = false;
        this.files.forEach((element,index)=>{
          if(element==file){
             this.files.splice(index,1);
          }
        });

      }
    );
  }
}
