var pathArray = window.location.pathname.split('/');
var appName = pathArray[2];

if (getCookie("id")) {
    console.log("Found ID Cookie: " + getCookie("id"));

    // Fetch bot metadata + authorization state, then render the page.
    fetch('/CollabCentral/' + appName + '/info')
        .then(res => res.json())
        .then(info => {
            document.title = info.label;
            document.getElementById("appLabel").innerHTML = info.label;
            document.getElementById("name").innerHTML = getCookie("displayName") || "";
            document.getElementById("appName").href = info.faviconUrl;
            document.getElementById("jobLink").href = "/CollabCentral/" + appName + "/sendMessage.html";

            var appIcon = document.getElementById("appIcon");
            appIcon.src = info.iconUrl;
            appIcon.style.maxHeight = "150px";
            appIcon.style.maxWidth = "150px";

            if (!info.authorized) {
                document.getElementById("unauthorizedPanel").classList.remove("hidden");
                return;
            }

            document.getElementById("jobsPanel").classList.remove("hidden");
            initJobTables();
        })
        .catch(err => console.error("Failed to load /info:", err));
} else {
    console.log("No ID Cookie found.");

    var randomNumber = Math.random().toString();
    randomNumber = randomNumber.substring(2, randomNumber.length);
    fetch('/CollabCentral/' + appName + '/authUrl')
        .then(res => res.text())
        .then((res) => {
            window.location.href = res + randomNumber;
        });
}

function initJobTables() {
    $('#runningJobs').dataTable({
        ajax: {
            url: '/CollabCentral/' + appName + '/jobs/list/running',
            dataSrc: ''
        },
        columns: [
            { data: 'senderDisplayName' },
            { data: 'appName' },
            { data: 'startTime' },
            { data: 'totalRecipients' },
            {
                data: 'completedRecipients',
                render: function (val, type, row) {
                    if (type !== 'display' || row.jobId === undefined || row.jobId === null) return val;
                    return val + ' <a href="/CollabCentral/' + appName + '/jobDetail.html?jobId=' + encodeURIComponent(row.jobId) + '" style="margin-left: 0.5em; font-size: 0.85em;">view</a>';
                }
            }
        ],
        searching: false,
        info: false,
        ordering: false,
        paging: false
    });

    $('#scheduledJobs').dataTable({
        ajax: {
            url: '/CollabCentral/' + appName + '/jobs/list/scheduled',
            dataSrc: ''
        },
        columns: [
            { data: 'senderDisplayName' },
            { data: 'appName' },
            { data: 'message' },
            { data: 'totalRecipients' },
            { data: 'scheduledFor' }
        ],
        searching: false,
        info: false,
        ordering: false,
        paging: false
    });

    $('#completedJobs').dataTable({
        ajax: {
            url: '/CollabCentral/' + appName + '/jobs/list/completed',
            dataSrc: ''
        },
        columns: [
            {
                data: 'jobId',
                render: function (jobId) {
                    if (jobId === undefined || jobId === null) return '';
                    return '<a href="/CollabCentral/' + appName + '/jobDetail.html?jobId=' + encodeURIComponent(jobId) + '">#' + jobId + '</a>';
                }
            },
            { data: 'senderDisplayName' },
            { data: 'appName' },
            { data: 'message.english.html' },
            { data: 'startTime' },
            { data: 'endTime' },
            { data: 'stats.totalTime' },
            { data: 'stats.webexTime' },
            { data: 'stats.averageTime' },
            { data: 'stats.succeededMsgs' },
            { data: 'stats.totalMsgs' },
            { data: 'stats.succeededMsgPct' }
        ],
        searching: false,
        info: false,
        ordering: false,
        paging: false
    });
}

function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
