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

rwthapp.updater = (function () {
    // Initialise persistent storage
    var storage = new rwthapp.Storage('updater');
    storage.addAttribute('lastVersion');

    // Store information if version was incremented to display changelog if necessary
    var versionUpdate = false;

    // Contains all update routines in form of an object { version: "x.x.x.x", action: function() {} }.
    // All updates which have a version greater than the currently saved app version are applied,
    // except for those where version is greater than the current app version (so "future" updates are not applied).
    // So to add an update procedure, use the new version number from the config file as version.
    var updates = [
        {
            version: "1.0.0",
            action: function () {
                clearLocalStorage();
            }
        },
    ];

    var compare = function (a, b) {
        return rwthapp.util.versionCompare(a.version, b.version);
    };

    var clearLocalStorage = function () {
        localStorage.clear();
    };

    var performUpdates = function () {
        return new Promise(function (resolve, reject) {
            // Sort Updates-Array to ensure correct order
            updates.sort(compare);

            var lastVersion = storage.getLastVersion();
            var currentVersion = rwthapp.options.getVersionNumber();

            if (lastVersion === null) {
                // Fresh installation, or version < 1.0.0, clean up localStorage either way
                clearLocalStorage();
            } else {
                for (var i = 0; i < updates.length; i++) {
                    // Apply all updates since lastVersion, ignore updates with version greater than currentVersion
                    if (rwthapp.util.versionCompare(lastVersion, updates[i].version) < 0
                        && rwthapp.util.versionCompare(currentVersion, updates[i].version) >= 0) {
                        updates[i].action(updates[i].version);
                    }
                }

                // Check if a changelog should be displayed (if available)
                if (rwthapp.util.versionCompare(lastVersion, currentVersion) < 0) {
                    versionUpdate = true;
                }
            }

            storage.setLastVersion(currentVersion);

            resolve();
        });
    };

    var generateChangelog = function (version, changes) {
        if (changes === undefined) {
            changes = rwthapp.langStrings.changelog[version];
        }

        if (changes && changes.length > 0) {
            var message = '<div class="changelog"><h5>Changelog ' + version + '</h5><ul>';

            for (var i = 0; i < changes.length; i++) {
                if (changes[i]) {
                    message += '<li>' + changes[i] + '</li>';
                } else {
                    // Add space if empty entry supplied
                    message += '<br />';
                }
            }

            message += '</ul></div>';

            return message;
        }

        return null;
    };

    var showChangelogIfUpdated = function () {
        // Only show changelog if this is the first app start after an update
        if (versionUpdate) {
            var message = generateChangelog(rwthapp.options.getVersionNumber());
            if (message) {
                rwthapp.notifications.showDialogWithFixedFooter(message);
            }
        }
    };

    var showChangelog = function () {
        var message = generateChangelog(rwthapp.options.getVersionNumber());
        if (message) {
            rwthapp.notifications.showDialogWithFixedFooter(message);
        } else {
            rwthapp.notifications.showDialog(rwthapp.localization.getLocalizedString("changelog.notFound"));
        }
    };
    
    return {
        performUpdates: performUpdates,
        showChangelogIfUpdated: showChangelogIfUpdated,
        showChangelog: showChangelog,
    };
})();