class UserEntry {
    constructor(username, isMember, rowElement) {
        this.username = username;
        this.isMember = isMember;
        this.rowElement = rowElement;
        this.buttonElement = $(rowElement).find(".toggleMembershipButton");
        if (isMember) {
            $(this.buttonElement).click(() => this.onClickLeave());
        } else {
            $(this.buttonElement).click(() => this.onClickJoin());
        }
    }

    onClickLeave() {
        this.isMember = false;
        $(this.buttonElement).off("click");
        $(this.buttonElement).click(() => this.onClickJoin());
        $(this.rowElement).prependTo($("#tableNonMembers").find("tbody"));
        this.setButtonAppearanceJoinGroup();
        if (membersTableIsEmpty()) {
            showEmptyTableNotice();
        }
        disableCreateGroupButton();
    }

    onClickJoin() {
        this.isMember = true;
        $(this.buttonElement).off("click");
        $(this.buttonElement).click(() => this.onClickLeave());
        $(this.rowElement).prependTo($("#tableMembers").find("tbody"));
        this.setButtonAppearanceLeaveGroup();
        hideEmptyTableNotice();
        enableCreateGroupButton();
    }

    setButtonAppearanceLeaveGroup() {
        this.buttonElement.removeClass("btn-danger btn-success btn-secondary");
        this.buttonElement.addClass("btn-danger");
        this.buttonElement.empty();
        this.buttonElement.html(
            '<i class="bi-person-fill-x"></i> Cancel'
        );
    }

    setButtonAppearanceJoinGroup() {
        this.buttonElement.removeClass("btn-danger btn-success btn-secondary");
        this.buttonElement.addClass("btn-success");
        this.buttonElement.empty();
        this.buttonElement.html(
            '<i class="bi-person-fill-add"></i> Add'
        );
    }
}

function showErrorMessage(message) {
    $("nav").after([
    '<div class="alert alert-danger alert-dismissible" role="alert">',
        `<div>${message}</div>`,
        '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
    '</div>'
    ].join(''));
}

function getGroupMembers() {
    let groupMembers = [];
    for (entry of $(membersTable).find(".userEntry")) {
        groupMembers.push(entry.id);
    }
    return groupMembers;
}

function getGroupName() {
    return $(groupNameInput).val();
}

function getUserEntries() {
    let userEntries = [];
    for (let entry of nonMembersTable.find("tbody").find(".userEntry")) {
        userEntries.push(new UserEntry(
            entry.id,
            false,
            entry
        ));
    }

    return userEntries;
}

function membersTableIsEmpty() {
    return $(membersTable).find("tbody").find(".userEntry").length === 0
}

function hideEmptyTableNotice() {
    if (emptyTableNotice.parent().length != 0) {
        emptyTableNotice.remove();
    }
}

function showEmptyTableNotice() {
    if (emptyTableNotice.parent().length == 0) {
        $(membersTable).find("tbody").append($(emptyTableNotice));
    }
}

function disableCreateGroupButton() {
    if ($(groupNameInput).val().length == 0 || membersTableIsEmpty()) {
        createGroupButton[0].disabled = true;
    }
}

function enableCreateGroupButton() {
    if ($(groupNameInput).val().length > 0 && !membersTableIsEmpty()) {
        createGroupButton[0].disabled = false;
    }
}

function createGroupButtonOnClick() {
    $.ajax({
        url: `/api/group/${getGroupName()}`,
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify({
            "members": getGroupMembers()
        }),
        dataType: "json",
    }).done(function() {
        window.location.replace(window.location.origin + `/groups/update/${getGroupName()}`);
    }).fail(function(xhr, status, errorThrown) {
        console.log(`Error: ${errorThrown}`);
        console.log(`Status: ${status}`);
        displayTextInputError(xhr.responseJSON['message']);
    });
}

function displayTextInputError(message) {
    $(createGroupButton).after([
    '<div class="alert alert-danger alert-dismissible m-2" role="alert">',
        `<div>${message}</div>`,
        '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
    '</div>'
    ].join(''));
}

let nonMembersTable = undefined;
let membersTable = undefined;
let entries = undefined;
let emptyTableNotice = undefined;
let createGroupButton = undefined;
let groupNameInput = undefined;

$(document).ready(function() {
    nonMembersTable = $("#tableNonMembers");
    membersTable = $("#tableMembers");
    entries = getUserEntries();
    emptyTableNotice = $("#emptyTableNotice");
    createGroupButton = $("#createGroupButton");
    groupNameInput = $("#groupNameInput");
    disableCreateGroupButton();
    $(groupNameInput).on("input", function() {
        enableCreateGroupButton();
        disableCreateGroupButton();
    });
    createGroupButton.click(createGroupButtonOnClick);
});
