import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ucapAnimations } from '../animations';
import { FileEventJson } from '@ucap-webmessenger/protocol-event';
import { FileViewerType } from '../types/file-viewer.type';
import { FileType } from '@ucap-webmessenger/protocol-file';
import { FileDownloadItem } from '@ucap-webmessenger/api-common';

@Component({
  selector: 'ucap-file-viewer',
  templateUrl: './file-viewer.component.html',
  styleUrls: ['./file-viewer.component.scss'],
  animations: ucapAnimations,
})
export class FileViewerComponent implements OnInit {
  @Input()
  fileInfo: FileEventJson;

  @Input()
  fileDownloadUrl: string;

  @Output()
  download = new EventEmitter<FileDownloadItem>();

  @Output()
  closed = new EventEmitter<void>();

  FileViewerType = FileViewerType;

  constructor() {}

  ngOnInit() {}

  detectFileViewerType(fileInfo: FileEventJson): FileViewerType {
    switch (fileInfo.fileType) {
      case FileType.Image:
        return FileViewerType.Image;
      case FileType.Sound:
        return FileViewerType.Sound;
      case FileType.Video:
        return FileViewerType.Video;
      default:
        if (this.isSoundFile(fileInfo.fileExt)) {
          return FileViewerType.Sound;
        }
        return FileViewerType.Binary;
    }
  }
  onDownload(fileDownloadItem: FileDownloadItem): void {
    this.download.emit(fileDownloadItem);
  }

  onClosedViewer(): void {
    this.closed.emit();
  }

  private isSoundFile(fileExt: string): boolean {
    return -1 !== ['mp3'].indexOf(fileExt);
  }
}
