import { atom, selector } from 'recoil'

export interface RawLikeEvent {
  e: number,
  episode: number,
  likes: number,
  s: number,
}

export interface LikeEvent extends RawLikeEvent {
  iLiked: boolean,
}

export const myLikesState = atom<Array<RawLikeEvent>>({
  default: [],
  key: 'myLikesState',
})

export const totalLikesState = atom<Array<RawLikeEvent>>({
  default: [],
  key: 'totalLikesState',
})

const transformedLikesState = selector({
  get: ({ get }) => {
    const totalLikes = get(totalLikesState)
    const myLikes = get(myLikesState)

    const likes: Array<LikeEvent> = totalLikes.map((like) => ({
      ...like,
      iLiked: myLikes.findIndex(({ episode }) => episode === like.episode) !== -1,
    }))

    return likes
  },
  key: 'transformedLikesState',
})

export const sortTypeState = atom<'asc' | 'desc'>({
  default: 'asc',
  key: 'sortTypeState',
})

export const filterTypeState = atom<'myLikes' | 'totalLikes'>({
  default: 'totalLikes',
  key: 'filterTypeState',
})

export const filteredLikesState = selector<Array<LikeEvent>>({
  get: ({ get }) => {
    const likes = get(transformedLikesState)
    const filterType = get(filterTypeState)

    return filterType === 'totalLikes' ? likes : likes.filter(({ iLiked }) => iLiked)
  },
  key: 'filteredLikesState',
})

