import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef,
  ChangeDetectorRef
} 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';
import { NGXLogger } from 'ngx-logger';

@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.0;
  currentTime = 0.0;
  volume = 0.1;
  loading = false;
  fileDownloadItem: FileDownloadItem;

  videoWidth = 0;
  videoHeight = 0;

  Math = Math;

  constructor(
    private changeDetectorRef: ChangeDetectorRef,
    private logger: NGXLogger
  ) {}

  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 {
    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 = this.audioPlayer.nativeElement.currentTime;
  }

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

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

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

    this.videoWidth = this.audioPlayer.nativeElement.videoWidth;
    this.videoHeight = this.audioPlayer.nativeElement.videoHeight;
  }

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

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