import { $store } from "@racletteCore"
import type { Composition } from "@shared/types/core/Composition.types"
import type { InteractionLink } from "@shared/types/core/InteractionLink.types"
import { pipe, values, find } from "ramda"

const compositionPathCache: Record<string, Composition> = {}

const pathExistsInValues = (
  path: string,
  pathObj: Record<string, string>,
): boolean => Object.values(pathObj).some((value) => value === path)

// TODO: outsource to a better place
type LocaleObject = {
  default: string
  de: string
  en: string
  es: string
}

// TODO: outsource to a better place
const getLocalizedName = (localeObject: LocaleObject) => {
  const locale = $store.getState(["ui", "locale"])
  const localeName =
    localeObject[locale] || localeObject[locale.split("-")?.[0]]

  if (localeName) {
    return localeName
  }

  return localeObject.default
}

const getCompositionById = (id: string): Composition | undefined => {
  const compositions = $store.getState("compositions")
  const composition = compositions[id]

  return composition
}

// TODO: rename to get**Localized**CompositionPathById
const getCompositionPathById = (id: string): string | undefined => {
  const composition = getCompositionById(id)

  if (composition) {
    return getLocalizedName(composition.pathname)
  }
}

// TODO: implement method for: => consider /krake === /el-krako

const getCompositionByPath = (path: string): Composition | undefined => {
  if (compositionPathCache[path]) {
    return compositionPathCache[path]
  }
  const compositionLookup = $store.getState("compositions")

  if (Object.keys(compositionLookup).length === 0) {
    return undefined
  }

  const found: Composition | undefined = pipe(
    values,
    find((item) => pathExistsInValues(path, item.pathname)),
  )(compositionLookup)

  if (found) {
    compositionPathCache[path] = found
  }

  return found
}

const getCompositionIdByPath = (path: string): string | undefined =>
  getCompositionByPath(path)?._id

export {
  getLocalizedName,
  getCompositionById,
  getCompositionPathById,
  getCompositionIdByPath,
  getCompositionByPath,
}
