import { postJson, showRequestError } from './api/base.js';

jQuery(document).ready(() => {
    const $ = jQuery;
    let data = {};
    try {
        data = JSON.parse($('#alert-team-data').text());
    } catch (e) {
        // Ignore error
    }

    async function respondToInvitation(event) {
        $(this).prop('disabled', true);
        try {
            const inSessionResponse = await postJson(data.in_session_url, {
                short_name: this.dataset.shortName,
            });
            if (inSessionResponse.response.team_id !== null) {
                if (this.dataset.confirmMoveTeamsMsg && !window.confirm(this.dataset.confirmMoveTeamsMsg)) {
                    $(this).prop('disabled', false);
                    return;
                }
            }

            const invitationResponse = await postJson(data.invitation_url, {
                team_id: this.dataset.teamId,
                accepted: event.data.accepted,
                csrf_token: data.csrf_token,
            });
            if (invitationResponse.response.team_url) {
                window.location.href = invitationResponse.response.team_url;
            } else {
                window.location.reload();
            }
        } catch (err) {
            showRequestError($(this), err);
            $(this).prop('disabled', false);
        }
    }

    $('.accept-invitation').on('click', { accepted: true }, respondToInvitation);
    $('.decline-invitation').on('click', { accepted: false }, respondToInvitation);
});
