import { $store } from "@racletteCore"
import type { Composition } from "@shared/types/core/Composition.types"
import type { InteractionLink } from "@shared/types/core/InteractionLink.types"
import type { ProjectConfiguration } from "../store/types"
import { useLocalStorage } from "@vueuse/core"

const setupSpace = async (
  compositions: Composition[],
  interactionLinks: InteractionLink[],
  projectConfig: ProjectConfiguration,
) => {
  const userTheme = useLocalStorage<string>("user-theme", null)
  let sessionTheme = userTheme.value
  // set compositions
  if (Array.isArray(compositions) && compositions.length > 0) {
    await $store.dispatch({
      type: "compositions/add",
      payload: compositions,
    })
  }
  // set interactionLinks
  if (Array.isArray(interactionLinks) && interactionLinks.length > 0) {
    await $store.dispatch({
      type: "interactionLinks/set",
      payload: interactionLinks,
    })
  }

  // set projectConfig
  if (projectConfig?.browser?.ui) {
    await $store.dispatch({
      type: "ui/update",
      payload: projectConfig.browser.ui,
    })
  }

  if (!userTheme.value) {
    let theme = "light"
    if (
      window.matchMedia &&
      window.matchMedia("(prefers-color-scheme: dark)").matches
    ) {
      theme = "dark"
    }

    sessionTheme = theme
  }
  await $store.dispatch({
    type: "ui/update",
    payload: { theme: sessionTheme },
  })
}

/**
 * setUserBrowserConfig
 *
 * @param { string } project, the project id
 * @param { object } config, the config object
 * @param { object } $store, our rx Store instance
 * @return { void }
 *
 * will apply a given config object to the application state.
 */
const setUserBrowserConfig = (userConfig, $store) => {
  // early return if we didn't receive project and its configuration
  if (!userConfig._source?.config) {
    return
  }
  const config = userConfig._source?.config

  if (!config) {
    return
  }
  $store.dispatch({
    type: "project/addConfig",
    payload: userConfig,
  })
  // add browser ui configuration to store
  if (config?.browser?.ui) {
    $store.dispatch({
      type: "ui/update",
      payload: config.browser.ui,
    })
  }
}

export { setUserBrowserConfig, setupSpace }
