<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 userid = localStorage.getItem('jf_userid')
    const data = await jfapi.GetNextUp(userid || '')
    if (data !== null) {
      for (const item of data.Items) {
        if (userid === null) {
          window.location.href = '/login'
        }
        feed.push({
          title: item.SeriesName !== undefined ? item.SeriesName : '',
          subtext: `S${item.ParentIndexNumber}:E${item.IndexNumber} - ${item.Name}`,
          image: getImageLink(item),
          summary: item.Overview,
          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: '',
          seriesId: item.SeriesId,
          type: item.Type,
        })
      }
      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>
