/*global LlamaRun _config*/

var LlamaRun = window.LlamaRun || {};
LlamaRun.map = LlamaRun.map || {};

(function runScopeWrapper($) {
    var authToken;
    LlamaRun.authToken.then(function setAuthToken(token) {
        if (token) {
            authToken = token;
        } else {
            window.location.href = '/signin.html';
        }
    }).catch(function handleTokenError(error) {
        alert(error);
        window.location.href = '/signin.html';
    });
    function requestLlama(pickupLocation) {
        $.ajax({
            method: 'POST',
            url: _config.api.invokeUrl + '/run',
            headers: {
                Authorization: authToken
            },
            data: JSON.stringify({
                PickupLocation: {
                    Latitude: pickupLocation.latitude,
                    Longitude: pickupLocation.longitude
                }
            }),
            contentType: 'application/json',
            success: completeRequest,
            error: function ajaxError(jqXHR, textStatus, errorThrown) {
                console.error('Error requesting run: ', textStatus, ', Details: ', errorThrown);
                console.error('Response: ', jqXHR.responseText);
                alert('Une erreur est survenue lors de votre demande de llama:\n' + jqXHR.responseText);
            }
        });
    }

    function completeRequest(result) {
        console.log('Response received from API: ', result);
        displayUpdate('Le llama ' + result.llama["Name"] + ' de type ' + result.llama["Gender"] + ' est en route pour votre run.');
        animateArrival(function animateCallback() {
            displayUpdate(result.llama["Name"] + ' est arrivé. Yeehaw !');
            LlamaRun.map.unsetLocation();
            $('#request').prop('disabled', 'disabled');
            $('#request').text('Nouveau run');
        });
    }

    // Register click handler for #request button
    $(function onDocReady() {
        $('#request').click(handleRequestClick);
        $('#signOut').click(function() {
            LlamaRun.signOut();
            alert("Vous avez été déconnecté.");
            window.location.href = "/signin.html";
        });
        $(LlamaRun.map).on('pickupChange', handlePickupChanged);

        LlamaRun.authToken.then(function updateAuthMessage(token) {
            if (token) {
                displayUpdate('Vous êtes authentifié. Cliquez pour voir <a href="#authTokenModal" data-toggle="modal">jeton d\'authentification</a>.');
                $('.authToken').text(token);
            }
        });

        if (!_config.api.invokeUrl) {
            $('#noApiMessage').show();
        }
    });

    function handlePickupChanged() {
        var requestButton = $('#request');
        requestButton.text('Run');
        requestButton.prop('disabled', false);
    }

    function handleRequestClick(event) {
        var pickupLocation = LlamaRun.map.selectedPoint;
        event.preventDefault();
        requestLlama(pickupLocation);
    }

    function animateArrival(callback) {
        var dest = LlamaRun.map.selectedPoint;
        var origin = {};

        if (dest.latitude > LlamaRun.map.center.latitude) {
            origin.latitude = LlamaRun.map.extent.minLat;
        } else {
            origin.latitude = LlamaRun.map.extent.maxLat;
        }

        if (dest.longitude > LlamaRun.map.center.longitude) {
            origin.longitude = LlamaRun.map.extent.minLng;
        } else {
            origin.longitude = LlamaRun.map.extent.maxLng;
        }

        LlamaRun.map.animate(origin, dest, callback);
    }

    function displayUpdate(text) {
        $('#updates').append($('<li>' + text + '</li>'));
    }
}(jQuery));
