import {Component, Input, OnInit, Output, EventEmitter} from '@angular/core';
import {File} from '../file';
import {Directory} from '../directory';
import {FileService} from '../file.service';
import {ApiService} from '../api.service';

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

  @Input() isFile: boolean;
  @Input() level: number;
  @Input() file: File;
  @Input() directory: Directory;
  @Input() trace: number[];
  deleting: boolean;
  isExpanded = false;

  @Output() deleteFile: EventEmitter<any> = new EventEmitter();
  @Output() deleteDir: EventEmitter<any> = new EventEmitter();

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

  ngOnInit(): void {
  }

  onDelete(): void {
    this.deleting = true;
    this.fileService.delete(this.isFile ? this.file : this.directory, this.isFile,
      JSON.parse(this.apiService.getToken()).username).subscribe(
      data => {
        console.log(data);
        if (this.isFile) {
          this.deleteFile.emit(this.file);
        } else {
          this.deleteDir.emit(this.directory);
        }
        this.deleting = false;
      }, error => {
        console.log(error);
      }
    );
  }

  addToTraceDir(dir: Directory): number[] {
    const arr = JSON.parse(JSON.stringify(this.trace));
    arr.push(this.directory.dirs.indexOf(dir));
    return arr;
  }

  addToTraceFile(file: File): number[] {
    const arr = JSON.parse(JSON.stringify(this.trace));
    arr.push(this.directory.files.indexOf(file));
    return arr;
  }

  deleteFileExec($event: any): void {
    const index = this.directory.files.indexOf($event, 0);
    if (index > -1) {
      this.directory.files.splice(index, 1);
    }
  }

  deleteDirExec($event: any): void {
    const index = this.directory.dirs.indexOf($event, 0);
    if (index > -1) {
      this.directory.dirs.splice(index, 1);
    }
  }
}
