import { provide, inject } from 'vue'
import type { InjectionKey } from 'vue'
import { INIT_OPTIONS_KEY, UPDATE_OPTIONS_KEY, THEME_KEY } from 'vue-echarts'

type Extract<T> = T extends InjectionKey<infer D> ? D : never

/** vue-echarts */

const useVueECharts = () => {
  const provideInitOption = (option: Extract<typeof INIT_OPTIONS_KEY>) => {
    provide(INIT_OPTIONS_KEY, option)
  }

  const injectInitOption = (init: Extract<typeof INIT_OPTIONS_KEY> | null = null) => {
    return inject(INIT_OPTIONS_KEY, init)
  }

  const provideUpdateOption = (option: Extract<typeof UPDATE_OPTIONS_KEY>) => {
    provide(UPDATE_OPTIONS_KEY, option)
  }

  const injectUpdateOption = (init: Extract<typeof UPDATE_OPTIONS_KEY> | null = null) => {
    return inject(UPDATE_OPTIONS_KEY, init)
  }

  const provideTheme = (option: Extract<typeof THEME_KEY>) => {
    provide(THEME_KEY, option)
  }

  const injectTheme = (init: Extract<typeof THEME_KEY> | null = null) => {
    return inject(THEME_KEY, init)
  }

  return {
    provideInitOption,
    injectInitOption,
    provideUpdateOption,
    injectUpdateOption,
    provideTheme,
    injectTheme,
  }
}

export default useVueECharts
