<script setup lang="ts">
import { useMainStore } from "@/stores/main";
import { storeToRefs } from "pinia";
import { onMounted } from "vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const mainStore = useMainStore();
const mainStoreRef = storeToRefs(mainStore);
const videos = mainStoreRef.readVideos;
const WS = mainStore.videosWebSocket;

const headers = [
  {
    title: t("videoTitle"),
    sortable: true,
    key: "title",
    align: "left",
  },
  {
    title: t("state"),
    sortable: true,
    key: "progress_state",
    align: "left",
  },
  {
    title: t("preview"),
    key: "id",
  },
];

function previewVideo(name: String) {
  window.open(`http://172.104.93.163:30080/${name}.mp4`);
}

onMounted(async () => {
  await mainStore.actionGetVideos();
  WS.onmessage = function (e) {
    console.log('onmessage',e);
    const data = e.data.split(':');
    mainStore.videos.map(e=>{
      if(e.stored_filename===data[0]) {
        e.progress_state = data[1]; // 影片狀態
        if (mainStore.userProfile && data[2]) {
          mainStore.userProfile.available_time = mainStore.userProfile.available_time - parseInt(data[2]); // 使用秒數
        }
      }
    })
  };
});

</script>

<template>
  <div>
    <v-toolbar light>
      <v-toolbar-title>
        <h3>{{ t("progress") }}</h3>
      </v-toolbar-title>
    </v-toolbar>
    <v-data-table
      :headers="headers"
      :items="videos"
      :sort-by="[{ key: 'id', order: 'desc' }]"
    >
      <template v-slot:item.progress_state="{ item }">
        <span v-if="item.raw.progress_state === 'SUCCESS'">
          <v-icon icon="check_circle" color="success" />
          完成
        </span>
        <span v-else-if="item.raw.progress_state === 'PENDING'">
          <v-icon icon="pending" color="warning" />
          等待中
        </span>
        <span v-else-if="item.raw.progress_state === 'STARTED'">
          <v-progress-circular
            indeterminate
            color="info"
            style="width: 20px"
          ></v-progress-circular>
          處理中
        </span>
        <span v-else>
          <v-icon icon="warning" color="error" />
          失敗
        </span>
      </template>
      <template v-slot:item.id="{ item }">
        <v-btn
          flat
          :disabled="item.raw.progress_state !== 'SUCCESS'"
          @click="previewVideo(item.raw.stored_filename)"
        >
          <v-icon icon="play_circle" />
        </v-btn>
      </template>
    </v-data-table>
  </div>
</template>

<style>
.v-data-table-footer {
  margin-top: 10px;
}
</style>
