import {Component, Input, ViewEncapsulation} from '@angular/core';
import {
  TuiButton,
  TuiDropdown,
  TuiDropdownOpen,
  TuiDropdownOptionsDirective,
  TuiIcon,
  TuiSlider
} from '@taiga-ui/core';
import {FormsModule} from '@angular/forms';
import {Oimg} from '../oimg/oimg';
import {TuiInputDateRange, TuiProgressBar} from '@taiga-ui/kit';

@Component({
  selector: 'video-player',
  imports: [
    TuiIcon,
    FormsModule,
    TuiButton,
    Oimg,
    TuiSlider,
    TuiProgressBar,
    TuiDropdownOptionsDirective,
    TuiDropdown,
    TuiDropdownOpen,
    TuiInputDateRange
  ],
  templateUrl: './video-player.html',
  styleUrl: './video-player.scss',
  encapsulation: ViewEncapsulation.None,
})
export class VideoPlayer {
  @Input() src: string = "";
  @Input() maxWidth: string = "";
  @Input() maxHeight: string = "";
  @Input() thumbnailOverwrite: string | undefined = undefined;

  playerActive = false

  videoLoaded = false

  videoPlayer: HTMLVideoElement | any = "";
  videoPlaying: boolean = false;
  videoFullscreen: boolean = false;
  watched: string = "00:00";
  controlShowed: boolean = false;
  videoMuted: boolean = false;
  videoVolBefMute: number = 0;

  videoHMSFormat(time: any) {
    let hours: any = Math.round(time / 3600)
    let minutes: any = Math.round(time / 60 - (hours * 60));
    let seconds: any = Math.round(time - (minutes * 60));
    if (seconds < 0) seconds += 60;

    if (hours < 10) hours = `0${hours}`;
    if (minutes < 10) minutes = `0${minutes}`;
    if (seconds < 10) seconds = `0${seconds}`;

    return hours == 0 ? `${minutes}:${seconds}` : `${hours}:${minutes}:${seconds}`;
  }

  jump(e: any) {
    let progressBar = e.target;
    const clickX = e.clientX - progressBar.getBoundingClientRect().left;
    const progressBarWidth = progressBar.clientWidth;
    const progressValue = (clickX / progressBarWidth) * progressBar.max;
    this.videoPlayer.currentTime = progressValue;
    progressBar.value = progressValue;
  }

  volume = 50
  showVolRange = false
  setVolume(volume: number) {
    this.videoPlayer.volume = volume / 100;
  }

  exitFullScreen() {
    document.exitFullscreen();
  }

  handleMute(){
    if(this.videoMuted) {
      this.videoPlayer.volume = this.videoVolBefMute / 100;
      this.videoMuted = false;
      this.volume = this.videoVolBefMute
    }else{
      this.videoPlayer.volume = 0;
      this.videoMuted = true;
      this.videoVolBefMute = this.volume;
      this.volume = 0
    }
  }

  playVideo() {
    this.playerActive = true
    this.videoPlaying = true;
    setTimeout(() => {
      this.videoPlayer.play();
    }, 100)
  }
}
