import { getBooleanOrDefault } from '../../utils'
import type { LegendInstance, LegendProps, Option } from './types'
import { isProdMode } from '/@/utils/env'

/**
 * 图例组件响应式 Hook
 * @param props 组件参数
 * @returns 组件响应式数据
 */
export function useLegendWidget<T extends LegendInstance>(props: LegendProps): [(instance: T) => void, T] {
    const instanceRef = ref<Nullable<T>>(null)

    function register(instance: T) {
        if (isProdMode()) {
            if (instance === unref(instanceRef)) {
                return
            }

            onUnmounted(() => {
                instanceRef.value = null
            })
        }

        instanceRef.value = instance
        props && instance?.setProps(props)
    }

    function getInstance(): T {
        const instance = unref(instanceRef)
        if (!instance) {
            console.warn('图例小部件还未加载完成')
        }
        return instance as T
    }

    return [
        register,
        {
            setProps: (props: LegendProps) => {
                getInstance()?.setProps(props)
            },
            setTitle: (title: string) => {
                getInstance()?.setTitle(title)
            },
            setOption: (option: Option) => {
                getInstance()?.setOption(option)
            },
            toggleShow: (show?: boolean) => {
                getInstance()?.toggleShow(getBooleanOrDefault(show))
            },
            toggleExpand: (expand?: boolean) => {
                getInstance()?.toggleExpand(getBooleanOrDefault(expand))
            },
        } as T,
    ]
}
