import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef,
} from '@angular/core';
import { ucapAnimations } from '../../animations';
import { FileEventJson } from '@ucap-webmessenger/protocol-event';
import { MatSlider, MatSliderChange } from '@angular/material';
import { FileDownloadItem } from '@ucap-webmessenger/api-common';

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

  @Input()
  fileDownloadUrl: string;

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

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

  @ViewChild('audioPlayer', { static: true })
  audioPlayer: ElementRef<HTMLVideoElement>;

  @ViewChild('timeSlider', { static: true })
  timeSlider: MatSlider;

  playing = false;
  duration = 0.01;
  currentTime = 0;
  volume = 0.1;
  loading = false;
  fileDownloadItem: FileDownloadItem;

  constructor() {}

  ngOnInit() {}

  onClickPlayOrPause(): void {
    if (this.loading) {
      return;
    }
    if (this.audioPlayer.nativeElement.paused) {
      this.audioPlayer.nativeElement.play();
    } else {
      this.currentTime = this.audioPlayer.nativeElement.currentTime;
      this.audioPlayer.nativeElement.pause();
    }
  }

  onChangeTimeSlider(e: MatSliderChange): void {
    console.log('onChangeTimeSlider', e.value);
    this.audioPlayer.nativeElement.currentTime = e.value;
  }

  onPlayingVideo(): void {
    this.playing = true;
    // this.duration = Math.floor(this.audioPlayer.nativeElement.duration);
  }

  onPauseVideo(): void {
    this.playing = false;
  }

  onTimeUpdateVideo(): void {
    this.currentTime = Math.floor(this.audioPlayer.nativeElement.currentTime);
  }

  onVolumeChangeVideo(): void {
    this.volume = Math.floor(this.audioPlayer.nativeElement.volume);
  }

  onLoadStartVideo(): void {
    this.loading = true;
  }

  onLoadedDataVideo(): void {
    this.loading = false;
    this.duration = Math.floor(this.audioPlayer.nativeElement.duration);
  }

  onClickDownload(): void {
    this.fileDownloadItem = new FileDownloadItem();
    this.download.emit(this.fileDownloadItem);
  }

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