import create from 'zustand'
import striptags from 'striptags'
import { isFuture, isPast } from 'date-fns'
import { slugify } from '../helpers/string'
import { getMetadataByKey, getPostByKey, getResourcesByKey, getPeertubeIDfromUrl, getEpisodeCode } from './helpers'
import { colours, defaultTheme } from '../assets/theme'

export const [useSeriesStore] = create(set => ({
  series: [],

  setSeries: seriesArray => {
    const allSeries = seriesArray.map(({ name, organizedEvents, posts, resources, banner, summary, members }) => {


      const allEpisodes = organizedEvents.elements.length ? organizedEvents.elements.map(ep => ({
        title: ep.title,
        beginsOn: ep.beginsOn,
        endsOn: ep.endsOn,
        description: ep.description,
        media: ep.media,
        image: ep.picture ? ep.picture.url : null,
        peertubeId: getPeertubeIDfromUrl(getMetadataByKey(ep, 'peertube:url')),
        code: getEpisodeCode(ep)
      })) : []

      const trailer = getResourcesByKey(resources, 'SERIES_TRAILER')?.[0]?.resourceUrl ?? null
      const theme = striptags(getPostByKey(posts, 'THEME'))
      const orgLinks = getResourcesByKey(resources, 'ORG_LINK:')?.map(link => link.title)

      console.log({ orgLinks })


      const series = {
        title: name,
        subtitle: striptags(summary),
        description: getPostByKey(posts, 'SERIES_INFO'),
        posts: posts.elements,
        resources: resources.elements,
        image: banner ? banner.url : '',
        episodes: {
          future: allEpisodes.filter(ep => isFuture(new Date(ep.endsOn))).sort((a, b) => new Date(a.beginsOn) - new Date(b.beginsOn)),
          past: allEpisodes.filter(ep => isPast(new Date(ep.endsOn))).sort((a, b) => new Date(a.beginsOn) - new Date(b.beginsOn))
        },
        slug: slugify(name),
        credits: getPostByKey(posts, 'SERIES_CREDITS'),
        trailer,
        links: getResourcesByKey(resources, 'SERIES_LINK') || [],
        theme: theme ? JSON.parse(theme) : defaultTheme,
        hosts: members.elements.filter(({ actor }) => actor.name !== 'streamappbot')
      }
      return series
    })

    set({ series: allSeries })
  }
}))