import xFetch from './xFetch';

const storage = sessionStorage;
const PREFIX = 'shuniu-cache-';

export default (url, options, time = 30 * 60 * 1000)=> {
    if (!options) {
        let cache = storage[PREFIX + url];
        if (cache) {
            try {
                cache = JSON.parse(cache);
                if (cache.time - Date.now() < time) {
                    return Promise.resolve(cache.data);
                }
            } catch (err) {
                console.error(err);
                clearCache(url);
            }
        }
    } else {
        let index = url.indexOf('?');
        if (index != -1) {
            clearCache(url.substr(0, index));
        } else {
            index = url.lastIndexOf('/');
            clearCache(url.substr(0, index));
        }
    }
    return xFetch(url).then(result=> {
        for (let i = 0; i < 3; i++) {
            try {
                storage[PREFIX + url] = JSON.stringify({
                    time: Date.now(),
                    data: result
                });
                break;
            } catch (err) {
                console.error(err);
                clearCache();
            }
        }
        return result;
    });
}

function clearCache(id) {
    console.log('clear cache ' + id);
    Object.keys(storage).forEach(key=> {
        if (key.indexOf(PREFIX + id) === 0) {
            storage.removeItem(key);
        }
    });
}

