import { getBooleanOrDefault, registerWidgetFactory, unpackWidgetInstance } from '../../utils'
import type { LegendInstance, LegendProps, Option } from './types'

// 组件名称
export const name = 'LegendWidget'

/**
 * 图例组件响应式 Hook
 * @param props 组件参数
 * @returns 组件响应式数据
 */
export function useLegendWidget<T extends LegendInstance, P extends LegendProps>(
    props: P,
): [(instance: T) => void, LegendInstance] {
    const instanceRef = ref<T>()
    const register = registerWidgetFactory(instanceRef, props)
    const { get, ...fns } = unpackWidgetInstance(instanceRef, name)

    return [
        register,
        {
            ...fns,
            setTitle: (title: string) => get()?.setTitle(title),
            setOption: (option: Option) => get()?.setOption(option),
            toggleExpand: (expand?: boolean) => get()?.toggleExpand(getBooleanOrDefault(expand)),
        },
    ]
}
