<script setup lang="ts">
import jfapi from '@/jfapi'
import MediaScroller from './MediaScroller.vue'
import type { FeedItem } from '@/feed'
import type { Item, View } from '@/jfapi'

const props = defineProps<{
  view: View
}>()

const Items = async (): Promise<FeedItem[]> => {
  return new Promise(async (resolve) => {
    const feed: FeedItem[] = []
    const userid = localStorage.getItem('jf_userid')
    const data = await jfapi.GetLatest(userid ? userid : '', props.view)
    if (data !== null) {
      console.log(data)
      for (const item of data) {
        const summary = ''
        if (userid === null) {
          window.location.href = '/login'
        }
        // const fullitem = await jfapi.GetItem(userid, item.Id)
        // if (fullitem === null) {
        //   continue
        // } else {
        //   summary = fullitem.Overview
        // }
        feed.push({
          title: item.SeriesName || item.Name,
          subtext: item.SeriesName
            ? `S${item.ParentIndexNumber}:E${item.IndexNumber} - ${item.Name}`
            : String(item.ProductionYear),
          image: getImageLink(item),
          summary: summary,
          // infoSubtext: item.SeriesName
          //   ? `S${item.ParentIndexNumber}:E${item.IndexNumber} - ${item.Name}`
          //   : fullitem.OriginalTitle != item.Name
          //     ? fullitem.OriginalTitle
          //     : '',
          infoSubtext: '',
          imdbRating: String(item.CommunityRating),
          runtime: getDisplayDuration(item.RunTimeTicks),
          date: String(item.ProductionYear),
          MPAA: item.OfficialRating,
          tag:
            item.UserData?.UnplayedItemCount !== undefined
              ? String(item.UserData.UnplayedItemCount)
              : '',
          itemId: item.Id,
        })
      }
      console.log('LatestMedia.vue =>', feed)
      resolve(feed)
    }
  })
}

function getImageLink(item: Item): string {
  if (item.SeriesId === undefined) {
    // using movie primary
    return jfapi.PrimaryImageUrl(item.Id, item.ImageTags.Primary ? item.ImageTags.Primary : '')
  } else {
    // using series primary
    return jfapi.PrimaryImageUrl(
      item.SeriesId,
      item.SeriesPrimaryImageTag ? item.SeriesPrimaryImageTag[0] : '',
    )
  }
}

function getDisplayDuration(ticks: number) {
  const totalMinutes = Math.round(ticks / 600000000) || 1
  const totalHours = Math.floor(totalMinutes / 60)
  const remainderMinutes = totalMinutes % 60
  const result = []
  if (totalHours > 0) {
    result.push(`${totalHours}h`)
  }
  result.push(`${remainderMinutes}m`)
  return result.join(' ')
}
</script>

<template>
  <MediaScroller :title="`Latest ${view?.Name}`" :feed-items="Items()" />
</template>
