import { shallowRef, watch } from 'vue'

/**
 * 本地存储类(基础版)
 */
export default class <T> {
    constructor(storage: Storage, key: string, value: T) {
        this.storage = storage
        this.storageKey = key
        this.source = value
        this.state = shallowRef(this.getValue())
        this.observe()
    }

    private readonly source // 原始数据
    private readonly storage
    readonly storageKey
    private state

    /**
     * 监听数据变化
     */
    private observe() {
        watch(this.state, (value) => {
            if (value === undefined || value === null) {
                this.storage.removeItem(this.storageKey)
            } else {
                const storageValue = JSON.stringify(value) // 注意数值长度过长会被自动转换为 String 类型
                this.storage.setItem(this.storageKey, storageValue)
            }
        })
    }

    /**
     * 获取数据
     * @returns 
     */
    getValue() {
        const storageValue = this.storage.getItem(this.storageKey)
        if (storageValue !== 'undefined' && storageValue !== null) {
            return JSON.parse(storageValue) as T
        } else {
            return this.source
        }
    }

    /**
     * 更新数据
     * @param value 
     */
    setValue(value: T) {
        this.state.value = value
    }

    /**
     * 获取响应数据
     * @returns 
     */
    getRef() {
        return this.state
    }

    /**
     * 重置数据
     */
    reset() {
        this.state.value = this.source
    }
}