/* CodeQ: an online programming tutor.
   Copyright (C) 2015 UL FRI

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */

/**
 * Created by robert on 9/17/15.
 *
 */

(function(){
    "use strict";
    var jqScreen = $("#screen_login"),
        jqNavBarRight = $('.nav.navbar-nav.navbar-right'),
        jqNavigationHomeBtn = $('#navigation-home'),
        jqAAILoginBtn = $('#aai_login_button'),
        jqSignupBtn = $('#signup_button'),
        jqSubmitLoginBtn = $("#submit"),
        jqLangSelect = jqScreen.find('.lang-select'),
        jqDisabledOverlay = $('#disabled');

    //the loginCallbackFunction is used here and in the AAI login as well
    codeq.loginCallbackFunction = function (data) {
        jqDisabledOverlay.css('display', 'none');
        jqDisabledOverlay.css('cursor', '');
        if (data.code !== 0) throw new Error('Login failed, code: ' + data.code + ', message: ' + data.message);

        //nav signed in...
        $('#signed-in-title').html(data.name||data.username||data.email||'undefined');
        //merge with profile page
        $('#profileUsername').html(data.username||data.email||'undefined');
        $('#profileName').html(data.name||'undefined');
        $('#profileEmail').html(data.email||'undefined');
        $('#profileJoined').html(new Date(data.joined).toLocaleString());
        $('#profileLastLogin').html(new Date(data["last-login"]).toLocaleString());

        //merge these settings into the already existing default settings
        var sett = data.settings;
        $.extend(codeq.settings, sett);
        if('gui_lang' in sett && sett['gui_lang'] in codeq.supportedLangs){
            codeq.setLang(sett['gui_lang']);
            $("#gui_lang_select").val(sett['gui_lang']);
        }
        $('#robot_address_input').val(codeq.settings['robot_address'] || '');
        if('gui_layout' in sett && ($.inArray(sett['gui_layout'], codeq.supportedLayouts) >= 0) ){
            codeq.setLayout(sett['gui_layout']);
            $("#gui_layout_select").val(sett['gui_layout']);
        }

        codeq.globalStateMachine.transition('language');
    };

    var loginFun = function(){
            jqDisabledOverlay.css('display', '');
            jqDisabledOverlay.css('cursor', 'wait');
            codeq.comms.connect()
                .then(function () {
                    return codeq.comms.login($('#username').val(), $('#password').val());
                })
                .then(codeq.loginCallbackFunction)
                .fail(function (reason) {
                    jqDisabledOverlay.css('display', 'none');
                    jqDisabledOverlay.css('cursor', '');
                    codeq.log.error('Login failed: ' + reason);
                    alert('Login request failed: ' + reason);
                })
                .done();
        },
        formInputs = $('#username, #password');

    codeq.globalStateMachine.register('login',{
        'jqScreen': jqScreen,

        'enter': function(){
            jqNavigationHomeBtn.off('click');//remove the click listener of this element here
            jqNavBarRight.css('display','none');//hide settings etc.
            $('#signed-in-title').html('');

            codeq.samlLogin = false;//remove saml login flag
            $('.saml-login-hide').css('display','');//if we login the normal way we want to show the change password buttons. if we enter the saml login they will be hidden

            //setup the signup button
            jqSignupBtn.on('click', function(e){
                codeq.globalStateMachine.transition('signup');
                e.preventDefault();
            });
            //setup the AAI login btn
            jqAAILoginBtn.on('click',function(e){
                codeq.globalStateMachine.transition('aailogin');
                e.preventDefault();
            });
            jqSubmitLoginBtn.on('click', loginFun);
            formInputs.on('keyup', function (ev) {
                if ((ev.keyCode || ev.which) == 13) {
                    jqSubmitLoginBtn.trigger('click');
                }
            });

            // setup language selection links
            jqLangSelect.on('click', function (e) {
                codeq.setLang($(this).data('lang'));
                e.preventDefault();
            });

            jqScreen.css('display', '');
            jqDisabledOverlay.css('display', 'none');
        },
        'exit' : function(){
            //remove the listener from the buttons specific to this page
            jqSubmitLoginBtn.off('click', loginFun);
            formInputs.off('keyup');
            jqSignupBtn.off('click');
            jqAAILoginBtn.off('click');
            jqLangSelect.off('click');

            jqScreen.css('display', 'none');
            $("#password").val('');
            //re-enable the click listener
            jqNavigationHomeBtn.on('click', function(e){
                codeq.globalStateMachine.transition('language');
                e.preventDefault();
            });
            jqNavBarRight.css('display','');
        }
    });
})();