import { None, Option, Some } from "@hazae41/result-and-option"
import { useLocation } from "@solidjs/router"
import { createContext, ParentComponent, useContext, createMemo } from "solid-js"
import z from "zod"

export const Locales = z.enum(["pt", "en"])
export type Locale = z.infer<typeof Locales>

export const LocaleContext = createContext<Option<Locale>>(new None())

const Provider: ParentComponent = ({ children }) => {
    const location = useLocation()

    const locale = createMemo(() => {
        const parsed = Locales.safeParse(location.pathname.substring(1, 3))
        return parsed.error ? new None() : new Some(parsed.data)
    })

    return <LocaleContext.Provider value={locale()}>{children}</LocaleContext.Provider>
}

export const useLocale = () => useContext(LocaleContext)

export default Provider
