var currentWorkItemId = 0;
var timeloggingWorkItemId = 0;
var isTimeLoggingStarted = false;
var baseAPIUrl = '';
$("#unauthorized").hide();
$("#licenseExpired").hide();
$("#main").hide();


async function renderTimeLoggingButton() {

    if (!currentWorkItemId || currentWorkItemId === 0) {
        return;
    }

    const container = $("#timeLoggingContainer");

    if (!isTimeLoggingStarted) {
        container.html(`
            <button id="startLogging" class="timesheet-action-btn" onclick="StartStopTimeLogging();">
                <i class="bi bi-play"></i>
                Start Time Logging
            </button>
        `);
        return;
    }

    const workItemUrl =
        `https://dev.azure.com/${await IndexLibrary.GetAccountNameAsync()}/_workitems/edit/${timeloggingWorkItemId}`;

    container.html(`
        <div class="workitem-pill"
             onclick="window.open(${IndexLibrary.escapeHtml(JSON.stringify(workItemUrl))}, '_blank')">
            <i class="bi bi-clock"></i>
            <span>${IndexLibrary.escapeHtml(timeloggingWorkItemId)}</span>
        </div>

        <button id="startLogging" class="timesheet-action-btn" onclick="StartStopTimeLogging();">
            <i class="bi bi-stop"></i>
            Stop Time Logging
        </button>
    `);
}


async function GetTimeTrackingStatus() {
    const response = await IndexLibrary.PostRequest({
        endpoint: "/api/Timesheet/IsTimeLoggingStarted",
        body: {
            organizationName: await IndexLibrary.GetAccountNameAsync(),
            userEmail: IndexLibrary.GetUserEmail()
        }
    });

    const json = await response.json();
    isTimeLoggingStarted = json.isStarted === true;

    if (isTimeLoggingStarted && json.workItemId) {
        timeloggingWorkItemId = Number(json.workItemId) || 0;
    } else {
        timeloggingWorkItemId = 0;
    }

    await renderTimeLoggingButton();
}

async function StartStopTimeLogging() {
    var timeLoggingEndpoint = "";
    if (isTimeLoggingStarted) {
        timeLoggingEndpoint = "/api/Timesheet/StopTimeLogging";
    } else {
        timeLoggingEndpoint = "/api/Timesheet/StartTimeLogging";
    }
    var currentProjectName = await IndexLibrary.GetCurrentProjectName();
    var currentProjectId = await IndexLibrary.GetCurrentProjectId();
    const response = await IndexLibrary.PostRequest({
        endpoint: timeLoggingEndpoint,
        body: {
            organizationName: await IndexLibrary.GetAccountNameAsync(),
            workItemId: currentWorkItemId,
            userEmail: IndexLibrary.GetUserEmail(),
            projectId: currentProjectId,
            projectName: currentProjectName
        }
    });

    const json = await response.json();
    if (json === true) {
        isTimeLoggingStarted = !isTimeLoggingStarted;
        timeloggingWorkItemId = currentWorkItemId;
        await renderTimeLoggingButton();
    }
}

$(document).ready(function () {
    IndexLibrary.InitializeSDK().then(async function () {
        const config = await IndexLibrary.GetExtensionConfig();
        baseAPIUrl = config.apiBaseUrl;
        const organizationName = await IndexLibrary.GetAccountNameAsync();

        const isUserLicensedResponse = await IndexLibrary.GetRequest({
            endpoint: `/api/License/IsUserLicensed?organizationName=${organizationName}&email=${IndexLibrary.GetUserEmail()}&moduleUserType=ptUserType`,
        });
        const isUserLicensed = await isUserLicensedResponse.text();

        if (isUserLicensed.toLowerCase() == 'false') {
            $("#main").hide();
            $("#licenseExpired").hide();
            $("#unauthorized").show();
            return;
        }

        const orgLicenseValidityResponse = await IndexLibrary.GetRequest({
            endpoint: `/api/License/IsOrgLicenseValid?organizationName=${organizationName}`,
        });
        const orgLicenseValidityData = await orgLicenseValidityResponse.text();

        if (orgLicenseValidityData.toLowerCase() == 'false') {
            $("#main").hide();
            $("#unauthorized").hide();
            $("#licenseExpired").show();
        } else {
            $("#main").show();
            $("#unauthorized").hide();
            $("#licenseExpired").hide();
            currentWorkItemId = await IndexLibrary.CurrentWorkItem();
            await GetTimeTrackingStatus();
            $("#addTime").on('click', function () {
                IndexLibrary.HandleTimeTrackingMenuOptionClick({ id: currentWorkItemId, apiUrl: baseAPIUrl });
            });
        }
    });

});

