(function(sugarApp) {
    "use strict";

    const moduleName = "SP_TemplateFolders";
    var loaded = false;

    /**
     * Shows the folder wizard.
     * @param folder The folder id
     */
    function showFolderWizard(folder) {
        var path    = Backbone.history.location.pathname + "modules/SP_TemplateFoldersManager/index.html";
        var name    = "sp_syncwizard_" + (new Date().valueOf()).toString() + "_" + Math.ceil(Math.random() * 10000);
        var params  = "scrollbars=0,toolbar=0,location=0,resizable=0,menubar=0,width=914,height=730";

        var w = window.open(path, name, params);

        if (w == null) {
            console.error("FATAL ERROR: Cannot open folder wizard!");
            alert("Error: cannot open sync wizard!");
            return;
        }

        w["access_token"]   = sugarApp.api.getOAuthToken();
        w["language"]       = sugarApp.lang.getLanguage();
        w["folder"]         = folder;
        w["new_folder"]     = folder == null;
    }

    // On sync complete
    sugarApp.events.on("app:sync:complete", function() {

        // Skip if module is already loaded...
        if (loaded) { return; }
        loaded = true;

        // On route list
        sugarApp.router.on("route:list", function(module) {
            if (module === moduleName) {
                // On start folder wizard button click
                sugarApp.controller.context.on("button:sp_startfolderwizard:click", function() {
                    var selected = this.get("mass_collection");
                    switch (selected.length) {
                        case 0:
                            showFolderWizard(null);
                            break;
                        case 1:
                            showFolderWizard(selected.models[0].get("id"));
                            break;
                        default:
                            // TODO: Show error message
                            console.error("");
                            break;
                    }
                });
            }
        });
    });

})(SUGAR.App);
