import util from 'util';
//内存数据
const memoryData = {};

const handler = {
    /***
     * 在全局对象的globalData里面获取数据
     * @param key[string]: 标识的key
     * @private
     */
    _getData(key) {
        //优先从内存获取数据，内存获取不到时再从磁盘获取
        if (memoryData[key]) return memoryData[key];
        let _localData = ''
        try {
            _localData = wx.getStorageSync && wx.getStorageSync(key)
        } catch (err) {
            console.log(err)
        }
        memoryData[key] = memoryData[key] || _localData || ''
        return memoryData[key];
    },
    /***
     * 在全局对象的globalData里面设置数据
     * @param key
     * @param val
     * @private
     */
    _setData(key, val, options) {
        if (memoryData[key]) {
            let old = memoryData[key];
            if (util.checkType(val) !== util.checkType(old)) {
                throw {
                    message: '保存数据时请确认前后数据类型一致'
                };
            } else {
                if (Array.isArray(old)) {
                    memoryData[key] = [];
                    val.forEach(item => {
                        memoryData[key].push(item);
                    });
                } else if (typeof old === 'object') {
                    memoryData[key] = util.assign({}, val);
                } else {
                    memoryData[key] = val;
                }
            }
        } else {
            memoryData[key] = val;
        }

        //如果数据指定在磁盘上也保存，则向磁盘也写数据
        if (options && options.localSave) {
            try {
                wx.setStorageSync && wx.setStorageSync(key, memoryData[key])
                // memoryData[key].local = true
            } catch (err) {
                console.log(err)
            }
        }
    },

    _getDataWithExpire(key) {
        const now = Math.round(+new Date() / 1000)
        const c = handler._getData(key)
        if (!c || now > c._expiredAt) {
            return null
        }
        return c.val
    },

    _setDataWithExpire(key, val, options) {
        const ttl = options.ttl || 600
        const now = Math.round(+new Date() / 1000)
        const _expiredAt = now + ttl
        handler._setData(key, {
            _expiredAt,
            val
        }, options)
    },
};

export default {
    getData: handler._getData,
    setData: handler._setData,
    getDataWithExpire: handler._getDataWithExpire,
    setDataWithExpire: handler._setDataWithExpire,
};