$(function () {

    var connection = new signalR.HubConnectionBuilder().withUrl('/codeHub').build();

    let $liveModeLink = $('#live-mode-link');
    let $liveModeStatus = $('#live-mode-status');
    let $usersList = $('#users-list');
    let $yourNameText = $('#your-name-text');
    let $yourColorText = $('#your-color-text');

    let isLive = false;

    let isLiveMode = function () {

        isLive = window.location.hash === '#live';

        $liveModeLink
            .toggleClass('btn-success text-white', isLive)
            .attr('href', isLive ? '#' : '#live');

        isLive ? $liveModeStatus.fadeIn() : $liveModeStatus.fadeOut();
    };

    let sendName = function (e) {

        let color = $yourColorText.val();

        $yourNameText.css('color', `${color}`);

        connection.invoke('SaveName', $yourNameText.val(), color);
    };

    let setHeight = function () {

        var editorHeight = $(window).height() - $('header').outerHeight() - $('footer').outerHeight();

        $('#editor').height(editorHeight - 2);
    };

    // events
    $(window).on('hashchange', isLiveMode);
    $(window).resize(setHeight);
    $('#your-name-text, #your-color-text').doneTyping(sendName);

    isLiveMode();
    setHeight();
    window.location.hash = '#live'; // set live mode on by default

    let isTeacher = window.location.hash === '#4ELQcUq7UnFGghAZCVr4Chr9JmtncigfkGu5WSf9';

    if (isTeacher) {
        $liveModeLink.hide();
        $liveModeStatus.hide();
    }

    let $editors = $('.ace_editor');

    if (isTeacher) {

        $editors.each(function (i, e) {

            let editor = ace.edit(e);

            editor.session.on('change', function () {

                let user = 'ryan';
                let code = editor.getValue();

                connection.invoke('UpdateCode', user, i, code).catch(function (err) {
                    return console.error(err.toString());
                });
            });
        });
    }

    connection.on('ReceiveCode', function (user, index, code) {

        if (!isTeacher && isLive) {

            let editor = ace.edit($editors[index]);

            editor.session.setValue(code);
        }
    });

    connection.on('UsersList', function (users) {

        let usersList = Object.values(users)
            .filter(u => u.name !== '')
            .map(u => `<span style="color: ${u.color};" title="${u.color}">${u.name}</span>`);

        $usersList.html(`<strong>${usersList.length} users online:</strong> ${usersList.join(', ')}`);

        // set the height in case we have more than one row
        setHeight();
    });

    connection.start().then(function () {

        sendName();

    }).catch(function (err) {
        return console.error(err.toString());
    });
});