import { GFun } from './GFun';
import { GConsole } from './GConsole';

export class GCache {
    private static gKey: string;

    /**
     * 初始化
     * @param keys 
     */
    public static init(keys: string[]): void {
        let i = 0;
        const len: number = keys.length;
        this.gKey = '';
        for (i; i < len; i++) {
            this.gKey += '_' + keys[i];
        }
    }

    /**
     * 写入缓存
     * @param key
     * @param value
     * @param type type 缓存类型 localStorage永久缓存 sessionStorage浏览器生命周期结束前'
     */
    public static writeCache(key: string, value: any, type = 'localStorage') {
        if (!window[type]) {
            GConsole.log(GFun.replace('webview不支持{0}', [type]));
            return;
        }
        window[type].setItem(key + this.gKey, value);
    }

    /**
     * 读取缓存
     * @param key
     * @param type type 缓存类型 localStorage永久缓存 sessionStorage浏览器生命周期结束前'
     * @return
     */
    public static readCache(key: string, type = 'localStorage'): string {
        if (!window[type]) {
            GConsole.log(GFun.replace('webview不支持{0}', [type]));
            return;
        }
        return window[type].getItem(key + this.gKey);
    }

    /**
     * 删除缓存
     * @param key
     * @param type 缓存类型 localStorage永久缓存 sessionStorage浏览器生命周期结束前
     */
    public static removeCache(key: string, type = 'localStorage'): string {
        if (!window[type]) {
            GConsole.log(GFun.replace('webview不支持{0}', [type]));
            return;
        }
        window[type].removeItem(key + this.gKey);
    }
}