import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FileService} from '../file.service';
import {File} from '../file';
import {Location} from '@angular/common';

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

  isActive = false;
  @Output() savedFile = new EventEmitter<boolean>();
  @Input() file: File;
  isUploading = false;

  constructor(public fileService: FileService, private location: Location) {
  }

  ngOnInit(): void {
  }

  setState(value: boolean): void {
    const text = document.getElementById('filenameInput') as HTMLTextAreaElement;
    this.isActive = value;
    if (value) {
      text.focus();
    }
  }

  submitFile(): void {
    this.isUploading = true;
    this.fileService.upload(this.file)
      .subscribe((response) => {
        this.isUploading = false;
        this.savedFile.emit(true);
        this.isActive = false;
        this.location.replaceState('/arena/file/' + response.key);
        console.log(response);
      }, (error) => {
        console.log(error);
        this.isUploading = false;
      });
  }
}
