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

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

function getImageLink(item: Item): string {
  if (item.ParentThumbItemId === undefined) {
    // using backdrop
    return jfapi.BackdropImageUrl(
      item.ParentBackdropItemId ? item.ParentBackdropItemId : '',
      item.ParentBackdropImageTags ? item.ParentBackdropImageTags[0] : '',
    )
  } else {
    // using thumb
    return jfapi.ThumbImageUrl(
      item.ParentThumbItemId,
      item.ParentThumbImageTag ? item.ParentThumbImageTag : '',
    )
  }
}

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="Next Up" landscape :feed-items="Items()" />
</template>
