define([
    'jquery',
    'msg/Msg',
    'unifi/service/location/locationService',
    'unifi/util/QueryString',
    //non-exporting
    'foundation',
    'retina'
], function (
    $,
    Msg,
    locationService,
    QueryString
) {
    'use strict';
    $(function () {
        $(document).foundation();

        var credentials = locationService.getSsoLoginCredentials(),
            $preload = $('#preload'),
            $message = $preload.find('#preload-message'),
            queryString = QueryString.getQueryStringObject(),
            redirectUrl = queryString && queryString.redirect && decodeURIComponent(queryString.redirect)
        ;

        // hotspot login
        var $LoginDescription = $('#HotspotLogin').find('#LoginDescription'),
            $ErrorMessage     = $('#HotspotLogin').find('.error-message');

        $.ajax({
            url: '/api/login',
            type: 'POST',
            data: JSON.stringify({
                for_sso: true,
                strict: true,
                sso_token: credentials.sso_token,
                ubic_uuid: credentials.ubic_uuid
            }),
            success: function(data, textStatus, xhr) {
                $.get('/api/self', {}, function(data) {
                    if (redirectUrl && (
                        redirectUrl.indexOf('/manage') === 0 ||
                        redirectUrl.indexOf('/hotspot') === 0 ||
                        redirectUrl.indexOf('/unifi') === 0
                    )) {
                        window.location.href = redirectUrl;
                    }
                    else {
                        locationService.gotoManagePage(data.last_site_name);
                    }
                });
            },
            error: function(xhr, textStatus, errorThrown) {
                var response = $.parseJSON(xhr.responseText),
                    error_msg;

                if(response.meta && response.meta.msg) {
                    error_msg = response.meta.msg;

                    if (error_msg === 'api.err.BetaQuotaReached') {
                        error_msg = Msg.E_BetaQuotaReached;
                    }
                    if (error_msg === 'api.err.Invalid') {
                        error_msg = Msg.E_InvalidSSOLogin;
                    }

                    $preload.addClass('error');
                    $message.text(error_msg);
                }
            }
        });
    });
});
