import type { MapboxConfig, MapboxInstance } from './index'
import { isProdMode } from '@/utils/env'

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

/**
 * 注册 Mapbox 实例
 * @param config Mapbox 配置项
 */
export function useMapbox<T extends MapboxInstance, P extends MapboxConfig>(
    config: P,
): [(instance: T) => void, MapboxInstance] {
    const instanceRef = ref<T>()

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

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

        instanceRef.value = instance
        config && instance?.setConfig(config)
    }

    function getInstance() {
        const instance = unref(instanceRef)
        if (!instance) {
            console.warn('Mapbox instance is undefined!')
        }
        return instance as T
    }

    return [
        register,
        {
            setConfig: (config: Partial<P>) => getInstance()?.setConfig(config),
            isReady: computed(() => instanceRef?.value?.isReady) as unknown as ComputedRef<boolean>,
        },
    ]
}
