<template>
  <div :class="`${customClass} relative`">
    <video
      ref="videoPlayer"
      v-if="videoUrl"
      class="video-js w-full h-full relative"
    ></video>
    <ts-image-loader
      v-else
      :customClass="'w-full h-full rounded'"
      :photoUrl="'/images/default-video.jpg'"
    >
    </ts-image-loader>

    <div
      v-if="!videoIsPlaying"
      class="flex flex-row items-center justify-center rounded absolute h-full w-full top-0 left-0 bg-black bg-opacity-60 z-index"
    >
      <ts-icon
        name="play-video"
        :customClass="`${iconSize} cursor-pointer`"
        @click="playVideo()"
      />
    </div>
  </div>
</template>
<script lang="ts">
import TsIcon from "../TsIcon/index.vue";
import videojs from "video.js";
import TsImageLoader from "../TsImageLoader";
import { onMounted, onUnmounted, ref } from "vue";

export default {
  components: {
    TsIcon,
    TsImageLoader,
  },
  props: {
    customClass: {
      type: String,
      default: "",
    },
    videoUrl: {
      type: String,
      default:
        "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4",
    },
    iconSize: {
      type: String,
      default: "h-[18px]",
    },
  },
  name: "TsVideo",
  setup(props: any) {
    let player: any = null;

    const videoPlayer = ref();
    const videoIsPlaying = ref(false);

    const options = {
      autoplay: false,
      controls: true,
      sources: [
        {
          src: props.videoUrl,
          type: "video/mp4",
        },
      ],
    };
    onMounted(() => {
      player = videojs(videoPlayer.value, options, () => {
        //
      });
    });

    const playVideo = () => {
      player?.play();
      videoIsPlaying.value = true;
    };

    onUnmounted(() => {
      player?.dispose();
    });

    return {
      videoPlayer,
      videoIsPlaying,
      playVideo,
    };
  },
};
</script>
