import { createContext, FC, useContext, useMemo } from 'react'
import { EnrichedEntity } from '../../../src/types'
import { ReactNodeLike } from 'prop-types'
import { factories } from './prepare'
import { useLocale } from '../../../src/hooks/useLocale'
import de from '../../../res/translation-de.json'
import nl from '../../../res/translation-nl.json'
import { Dict } from '../../../src/types'

const factoryNames: Record<'de' | 'nl', Dict<string>> = {
  de,
  nl
}

interface Props {
  children: ReactNodeLike
}

interface FactoryContextType {
  factories: EnrichedEntity[]
  findFactory(uid: string): EnrichedEntity | undefined
}

const defaultValues: FactoryContextType = {
  factories: [],
  findFactory() {
    return undefined
  }
}

const FactoryContext = createContext<FactoryContextType>(defaultValues)
export const useFactories = () => useContext(FactoryContext)

export const FactoryProvider: FC<Props> = ({ children }) => {
  const locale = useLocale()
  const internationalizedFactories = useMemo(() => {
    if (locale !== 'en')
      return factories.map(factory => ({
        ...factory,
        name: factoryNames[locale]?.[factory.href] ?? factory.name
      }))
    return factories
  }, [locale])

  //const zip = 'bY3BCsNACET/xlP30KY9NODHGFeKsNld1JR+fjeQHgrBQZiReWYKwmsa8wSjEHTgjjdYteIEi5RA+XQT9xRG1XuzSHsMGrI6Un5TZcmJ1XjTmG2+P0BftZmgWqupl4G9cOtd7DBjeyinhQzWlrciJyCfZjn0azMtRf4OUoRjfBmwk94X'
  //const zip = 'bU/RasMwDPwbP8UPXTboMvwxiqwVgWMbSR7t39cbTkm3YWHEnU53imAQTr6/dydgFNRhDS9u4xxmt1KyQNcqpOpNIGstYv4bdmy0aaBEaFIyo0cWbGyLLK9vE8QvyEjxGa1SsK/ifPEt7+AKZiS3oUNsW0tgRX4Ax5dchAKWWkl87QxN3A1H23+1br6CTNrSZxO3ldgSaTiu0nmhUX+jHck9zI5NwxhhTfQ0+c/lR/r3qXV+1EefO4+0XQ3I8SG9Aw=='
  //const zip = 'bVHBcgMhCP0bT+WQpD10Z/wYmqXG6SoO4mw+v+qmU206coAHPB+woqI9QX3vRlDJZnNN9myCj/ZiPmhTS/cklDOoYMyJRaHBxiuFbJNPBMrghEtcF1lOLw3qTlYWdDWN8asDVxTHsKPj2OPPrfh1ijGQ3oR3koOqhPTT+VQBWkRIO07R+UhQom/x65vxLrKQ9cIR0lYHq2qItsM3gdeyUbaNNl8WetgkcMRH+hGfBNO5G/0rcu76HXvEu1hHKLDfqtbnXBd//HNseaz4c4kp1dY4AsMuHnTTrYbSbw=='
  //const unzip = inflateRaw(Buffer.from(zip, 'base64'), {to: 'string'})
  //console.log(unzip)

  const findFactory = useMemo(() => {
    const detailsMap = Object.fromEntries(
      internationalizedFactories.map((detail: EnrichedEntity) => [detail.href, detail])
    )
    return (uid: string): EnrichedEntity | undefined => {
      return detailsMap[uid]
    }
  }, [internationalizedFactories])

  const value: FactoryContextType = useMemo(
    () => ({
      factories: internationalizedFactories,
      findFactory
    }),
    [findFactory, internationalizedFactories]
  )
  return <FactoryContext.Provider value={value}>{children}</FactoryContext.Provider>
}
