import $ from 'jquery';
import util from '../utils/util-basic.jsx';
import {urls} from '../constants.jsx';

var cachedBuildTime = localStorage.getItem('build-time');
var currentSession = {};

var dataAccess = {
    getBuildTime: function() {
        return cachedBuildTime;
    },
    checkBuildTime: function() {
        var buildTimeReq = $.ajax({
            url: urls.buildTime,
            method: 'GET',
            dataType: 'text',
            cache: false
        }).done(function(result) {
            if (result != cachedBuildTime) {
                localStorage.setItem('build-time', result);
                location.reload();
                // 需要做一下 "询问", 而不是强制reload @[  todo  ]{ihk14kbo_pi5qjshq_h9ewg}@
            }
        });
    },
    getTags: function() {
        if (!currentSession.tags) {
            return currentSession.tags = $.ajax({
                url: urls.tags,
                method: 'GET',
                data: {
                    buildTime: cachedBuildTime
                }
            }).done(result => (currentSession.tags = result));
        } else if(util.isAjaxCallback(currentSession.tags)) {
            return currentSession.tags;
        } else {
            return {
                done(fn) {
                    setImmediate(x => fn(currentSession.tags));
                }
            }
        }
    },
    getBackLinks() {
        if (!currentSession.backLinks) {
            return currentSession.backLinks = $.ajax({
                url: urls.backLinks,
                method: 'GET',
                data: {
                    buildTime: cachedBuildTime
                }
            })
            .done(result => (currentSession.backLinks = result));
        } else if (util.isAjaxCallback(currentSession.backLinks)) {
            return currentSession.backLinks;
        } else {
            return {
                done(fn) {
                    setImmediate(x => fn(currentSession.backLinks));
                }
            }
        }
    },
    getFileTree: function() {
        if (!currentSession.tree) {
            return currentSession.tree = $.ajax({
                url: urls.fileTree,
                method: 'GET',
                data: {
                    buildTime: cachedBuildTime
                }
            }).done(result => (currentSession.tree = result));
        } else if (util.isAjaxCallback(currentSession.tree)) {
            return currentSession.tree;
        } else {
            return {
                done(fn) {
                    setImmediate(x => fn(currentSession.tree));
                }
            }
        }
    }
};

export default dataAccess;