import { toRefs, computed } from 'vue'
import { useState } from './hook-state'
import * as env from '../types/instance.resolver'

export interface StateOption extends env.ResizeOption {
    namespace: string
    loading: boolean
    failure: boolean
}

export enum APP_SKY {
    COLLAPSED = 'APP_NAMESPACE_SKYLINE_COLLAPSED',
    DEVICE = 'APP_NAMESPACE_SKYLINE_DEVICE'
}

export async function setStorage<T>(key: APP_SKY, value: T) {
    return window.localStorage.setItem(key, JSON.stringify(value))
}

export function getStorage<T>(key: APP_SKY, defaultValue?: T): T {
    const jsonStr = window.localStorage.getItem(key)
    try {
        return jsonStr ? JSON.parse(jsonStr) : (defaultValue as T)
    } catch (err) {
        return defaultValue as T
    }
}

const { state, setState } = useState<StateOption>({
    namespace: 'el-sky',
    loading: true,
    failure: false,
    width: window.innerWidth,
    height: window.innerHeight,
    collapsed: getStorage(APP_SKY.COLLAPSED, false),
    device: getStorage(APP_SKY.DEVICE, 'PC')
})
export function useSkyConfiger() {
    const IsMobile = computed<boolean>(() => state.device === 'Mobile')
    const stateOption = computed<env.ResizeOption>(() => ({
        width: state.width,
        height: state.height,
        collapsed: state.collapsed,
        device: state.device
    }))

    async function setDevice(device: 'PC' | 'IPAD' | 'Mobile') {
        await setStorage(APP_SKY.DEVICE, device)
        return await setState({ device })
    }

    async function setCollapsed(collapsed: boolean) {
        await setStorage(APP_SKY.COLLAPSED, collapsed)
        return await setState({ collapsed })
    }

    async function setResize(data: { width: number; height: number }) {
        await setState({ width: data.width, height: data.height })
        if (data.width >= 1080) {
            await setCollapsed(false)
            return await setDevice('PC')
        } else if (data.width > 768) {
            await setCollapsed(true)
            return await setDevice('IPAD')
        } else {
            await setCollapsed(true)
            return await setDevice('Mobile')
        }
    }

    return { state, ...toRefs(state), IsMobile, stateOption, setState, setDevice, setCollapsed, setResize }
}
