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

rwthapp.util.initNamespace("templates.campus");

rwthapp.templates.campus.search = (function () {
    var timeoutHandle = null;
    var timeoutTime = 2000;
    var page;
    
    var queryOnStartup = false;

    var searchType;
    var apiCall;
    var templateName;
    var partialName;
    var templateLogic;

    // TODO in template: input type should be search, but causes several issues with the look of the input field

    var load = function (template, parameters) {
        page = template;
        searchType = parameters.type;
        templateLogic = template;

        var title = '';

        var tabletMode = { position: 'right', mainView: true };

        switch (searchType) {
            case "employees": apiCall = rwthapp.connection.api.campus.getEmployees;
                templateName = "campus.search.employees";
                title = rwthapp.localization.getLocalizedString("titles.searchEmployees");
                break;
            case "rooms": apiCall = rwthapp.connection.api.campus.getRooms;
                templateName = "campus.search.rooms";
                title = rwthapp.localization.getLocalizedString("titles.searchRooms");
                break;
            case "courses": apiCall = rwthapp.connection.api.campus.getCourses;
                templateName = "campus.search.courses";
                title = rwthapp.localization.getLocalizedString("titles.searchCourses");
                break;
        }

        partialName = templateName + ".result";

        if (!rwthapp.platformInfo.isTablet()) {

            tabletMode = null;
        }

        // If search parameter is included, execute search
        if (parameters.query && parameters.query.length > 1) {

            queryOnStartup = true;

            return apiCall(parameters.query, "").then(function (data) {

                return {

                    template: templateName,
                    parameters: {
                        query: parameters.query,
                        results: data
                    },
                    title: title,
                    tabletMode: tabletMode
                }; 
            });
        } else {
            queryOnStartup = false;

            return {
                template: templateName,
                title: title,
                tabletMode: tabletMode
            };
        }
    };

    var ready = function () {

        if (queryOnStartup || $('#results').children().length > 0) {

            $('#results').attr("style", "visibility: visible");
        } else {
            $('#searchInput').focus();
            // Trigger keyboard via plugin
            rwthapp.util.showKeyboard();
        }

        // User can manually start search
        $('#searchInput').on("keyup", function (e) {
            if (e.which === 13) {
                var query = $('#searchInput').val().trim();
                startSearch(query, "", true);
            } 
        });

        // Start search automatically after x seconds. 
        // Event triggered on every content change (keyboard autocomplete as well)
        $('#searchInput').on("input", function () {
            restartTimeout();
        });
    };

    var exit = function () {
        $('#searchInput').off("keyup");
        cancelTimeout();
    };

    var startSearch = function (query, filter, executedByUser) {
        cancelTimeout();

        if (query && query.length > 1) {
            if (executedByUser) {
                rwthapp.util.showLoadingScreen();
            }

            // Replace history state and append search string to restore search on back-navigation
            rwthapp.navigator.replaceCurrentHashWithoutNavigation(getCurrentPageUrlWithQuery(query));

            apiCall(query, filter).then(function (data) {
                // Lose focus if user started search explicitly (hide keyboard)
                if (executedByUser) {
                    if (rwthapp.platformInfo.isWindowsUniversal()) {
                        // blur does not work on Windows Phone (Universal)
                        $('#searchInput').focusout();
                    } else {
                        $('#searchInput').blur();
                    }
                }

                var result = {

                    template: templateName,
                    parameters: {
                        query: query,
                        results: data
                    }
                };

                $('#results').attr("style", "visibility: visible");
                $('#results').empty();

                for (var i = 0; i < data.length; i++) {
                    $("#results").append(rwthapp.templateRenderer.fetch(partialName, data[i]));
                }

                // Perform postprocessing (fixing icons, removing waves effect) if necessary
                rwthapp.templateRenderer.performPostprocessing();

                rwthapp.util.hideLoadingScreen();
            }).catch(function (error) {
                // Only react to error if the user explocitly started the search
                if (executedByUser) {
                    // Show error message
                    rwthapp.error.handleError(error, getCurrentPageUrlWithQuery(query));
                } 
            });
        } else if (executedByUser) {
            // Query too short
            rwthapp.notifications.showDialog(rwthapp.localization.getLocalizedString("campus.search.queryTooShort"));
        }
    };

    var cancelTimeout = function () {
        if (timeoutHandle !== null) {
            clearTimeout(timeoutHandle);
            timeoutHandle = null;
        }
    };

    var restartTimeout = function () {
        cancelTimeout();
        timeoutHandle = setTimeout(timeoutFunction, timeoutTime);
    };

    var timeoutFunction = function () {
        var query = $('#searchInput').val().trim();
        startSearch(query, "", false);
    };

    var getCurrentPageUrlWithQuery = function (query) {

        var result = '#campus.search?type=' + searchType + '&query=' + encodeURIComponent(query);

        return result;
    };

    return {
        load: load,
        ready: ready,
        exit: exit,
    };
})();