/// <reference path="../references.js" />

rwthapp.versionCheck = (function () {
    var storage = new rwthapp.Storage("versionCheck");
    storage.addAttribute("isDeprecated");
    storage.addAttribute("isNotSupported");

    storage.addAttribute("appNotSupportedVersion");
    storage.addAttribute("appDeprecatedVersion");

    var getAppVersion = function () {
        return rwthapp.options.getVersionNumber();
    };

    var performComparison = function () {
        var currentAppVersion = getAppVersion();

        storage.setIsNotSupported(false);
        storage.setIsDeprecated(false);

        if (rwthapp.util.versionCompare(currentAppVersion, storage.getAppNotSupportedVersion("0")) <= 0) {
            storage.setIsNotSupported(true);
        } else if (rwthapp.util.versionCompare(currentAppVersion, storage.getAppDeprecatedVersion("0")) <= 0) {
            storage.setIsDeprecated(true);
        }
    };

    var initialize = function () {
        return new Promise(function (resolve, reject) {
            rwthapp.connection.api.version().then(function (data) {

                // Save version numbers in local storage and compare them to current version
                storage.setAppDeprecatedVersion(data.AppDepricatedVersion);
                storage.setAppNotSupportedVersion(data.AppNotSupportedVersion);

                performComparison();

                resolve();
            }).catch(function () {
                // If a flag is set, perform comparison with cached values, avoids wrong messages after updating the app and being offline on startup
                if (storage.getIsDeprecated() || storage.getIsNotSupported()) {
                    performComparison();
                }

                resolve();
            });
        });
    };

    var isNotSupported = function () {
        return storage.getIsNotSupported(false);
    };

    var isDeprecated = function () {
        return storage.getIsDeprecated(false);
    };

    return {
        initialize: initialize,
        isNotSupported: isNotSupported,
        isDeprecated: isDeprecated,
    };
})();