"use strict";
App.addInitializer(function(options){
    if (window.location.href.indexOf("reset") > 0) {
        localStorage.clear();
        console.log("reset");
    }

    if (navigator.appVersion.indexOf("Mac") > 0) {
        App.keyboardMappings = {
            ctrl: "meta",
            ctrlTitle: "cmd",
            ctrlShift: "shift+meta",
            ctrlShiftTitle: "cmd+shift",
        };
    } else {
        App.keyboardMappings = {
            ctrl: "ctrl",
            ctrlTitle: "ctrl",
            ctrlShift: "ctrl+shift",
            ctrlShiftTitle: "ctrl+shift",
        };
    }

    App.DataModule.start();


    // pre-configuring
    App.options.debugAPI           = !!App.DataModule.Storage.getStrCache(null, "debug-api");
    App.options.defaultEntityWidth = 400;

    App.DataModule.CliopatriaAPI.start({
        apiRootPaths: options.musicLibrary.apiRootPaths,
        apiVersion: options.musicLibrary.apiVersion,
        dataVersion: options.musicLibrary.dataVersion,
        dataCaching: options.musicLibrary.dataCaching
    });

    App.NotificationsModule.start();
    App.ContextModule.start();
    App.RepresentationModule.start();
    App.MainRegionModule.start();
    App.TooltipModule.start();

    App.HelpModule.start();

    // Define context and context manager
    App.contextManager = new App.ContextModule.AppContextManager();
    App.context = new App.ContextModule.AppContext();

    try {
        App.contextManager.restoreFromStorage(App.context, "");
    } catch (e) {
        App.contextManager.restoreDefault("");
    }
    App.dynamicDefinitionProviderForCollections = new App.DataModule.DynamicDefinitionProviderForCollections();
    App.dynamicDefinitionProviderForRecordings  = new App.DataModule.DymanicDefinitionProviderForRecordings();
    App.dynamicDerivedConfigDataProvider  = new App.RepresentationModule.DynanicDerivedConfigDataProvider({
        configGridsByType: {
            "collection": App.context.get("state").get("musicCollectionGrid"),
            "recording":  App.context.get("state").get("musicRecordingGrid")
        }
    });

    App.PlayerModule.start();

    var saveContextToStorage = function() {
        App.contextManager.saveToStorage(App.context);
    };

    var throttledSaveAppContextToStorage = _.throttle(saveContextToStorage, 10000, {leading: false});

    App.context.bind("change", throttledSaveAppContextToStorage);

    $(window).on("beforeunload", saveContextToStorage);


    // Initialize main region
    App.mainRegionView = new App.MainRegionModule.MainRegionView({state: App.context.get("state"), el: ".app__main-region"});

    // Init main menu
    App.MainMenuModule.start();

    App.TooltipModule.convertTitlesToTooltips($("body"));
});
