import { useCache } from '@/hooks/useCache'
import axios from "@/config/axios";

const {wsCache} = useCache('sessionStorage')

export interface H5Pages {
    country: string
    language: string
    name: string
    logo: string
    favicon: string
    title: string
}

const defaultConfig: H5Pages = {
    country: 'US',
    language: 'en-us',
    name: 'Baltini',
    logo: '/favicon.ico',
    favicon: '/favicon.webp',
    title: 'Baltini App', 
}

const PAGE_CONFIG_KEY = 'pageConfig'

export const getH5PagesConfig = (): H5Pages => {
    return wsCache.get(PAGE_CONFIG_KEY);
}

const fetchH5PagesConfig = async () => {
    let res:H5Pages
    try {
        res = await axios.get({ url: '/member/app/config/get' })
    } catch (e) {
        res = {...defaultConfig}
    }
    return res
}

export const setupPageConfig = () => {
    fetchH5PagesConfig().then(res => {
        wsCache.set(PAGE_CONFIG_KEY, res)
        // set title
        document.title = res.title
        // set favicon
        const link = document.querySelector("link[rel*='icon']")  as HTMLLinkElement || document.createElement('link') as HTMLLinkElement
        link.type = 'image/x-icon'
        link.rel = 'shortcut icon'
        link.href = res.favicon
    })

}