$(function () {

    var connection = new signalR.HubConnectionBuilder()
        .withAutomaticReconnect()
        .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 isTeacher = window.location.hash === '#4ELQcUq7UnFGghAZCVr4Chr9JmtncigfkGu5WSf9';

    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 updateCode = function (editor, index) {

        let user = $yourNameText.val();
        let code = editor.getValue();

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

    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();

    if (isTeacher) {
        $liveModeLink.hide();
        $liveModeStatus.hide();
    } else {
        window.location.hash = '#live'; // set live mode on by default
    }

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

    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 => `<a target="_blank" href="/view/${u.id}" style="color: ${u.color};" title="${u.color}">${u.name}</a>`);

        $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();

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

            let editor = ace.edit(e);

            editor.session.on('change', function () {
                updateCode(editor, i);
            });

            // send initial code
            updateCode(editor, i);
        });

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