var _apiUrl = null;

function compareFunction(a, b) {
    if (a.Effort == undefined || b.Effort == undefined) {
        var aPollValue = a.PollValue.split('-');
        var bPollValue = b.PollValue.split('-');
        return bPollValue[0] - aPollValue[0] || b.State[0] - a.State[0] || bPollValue[bPollValue.length - 1].trim()[0] - aPollValue[aPollValue.length - 1].trim()[0] || b.ParentId - a.ParentId || a.Id - b.Id;
    } else {
        return b.Effort - a.Effort || b.State[0] - a.State[0] || b.ParentId - a.ParentId || a.Id - b.Id;
    }
}

function showOne(rowData) {
    if (rowData == undefined)
        return;
    var data = [];
    data.push({ name: "Edit in ADO", value: '<a target="_blank" href="https://tfs.intra.infineon.com/tfs/FactoryIntegration/ART%20SPS/_workitems/edit/' + rowData["Id"] + '">Edit in ADO ' + rowData["Id"] + '</a>' });
    for (const property in rowData) {
        if (rowData[property] == undefined)
            continue;
        data.push({ name: property, value: rowData[property].toString() });
    }
    $("#AllGrid").igGrid({
        autoGenerateColumns: true,
        dataSource: data,
        width: "100%",
        showHeader: false,
    });
}

function loadOne() {
    var selectedRow = $("#HeaderGrid").data("igGridSelection").selectedRow();
    if (selectedRow == undefined)
        return;
    var rowData = $("#HeaderGrid").data("igGrid").dataSource.dataView()[selectedRow.index];
    showOne(rowData);
}

function detailSelectionChangedRunInfo(evt, ui) {
    if (ui.row.index === 0)
        return;
    var rowData = ui.owner.grid.dataSource.dataView()[ui.row.index];
    showOne(rowData);
}

function getState(state) {
    var result;
    if (state == undefined)
        result = "9-Null";
    else if (state === "New")
        result = `1-${state}`;
    else if (state === "Active")
        result = `2-${state}`;
    else if (state === "Resolved")
        result = `3-${state}`;
    else if (state === "Closed")
        result = `4-${state}`;
    else if (state === "Removed")
        result = `5-${state}`;
    else
        result = `8-${state}`;
    return result;
}

function getPriority(workItemType, priority) {
    var result;
    if (workItemType === "Bug")
        result = "0-Bug";
    else if (priority == undefined || priority === 0)
        result = "9-Null";
    else if (priority === 1)
        result = `${priority}-High`;
    else if (priority === 2)
        result = `${priority}-Med`;
    else if (priority === 3)
        result = `${priority}-Low`;
    else if (priority === 4)
        result = `${priority}-TBD`;
    else
        result = "8-Not";
    return result;
}

function getPollValue(description, pollValue) {
    var result;
    if (pollValue == undefined || pollValue.Effort == undefined || pollValue.Effort.InverseAverage == undefined)
        result = "";
    else if (pollValue.Effort.InverseAverage >= 4)
        result = `${pollValue.Effort.InverseAverage} - 1-Highest (Most ${description}) - ${pollValue.Count} Vote(s)`;
    else if (pollValue.Effort.InverseAverage >= 3)
        result = `${pollValue.Effort.InverseAverage} - 2-High - ${pollValue.Count} Vote(s)`;
    else if (pollValue.Effort.InverseAverage >= 2)
        result = `${pollValue.Effort.InverseAverage} - 3-Medium - ${pollValue.Count} Vote(s)`;
    else if (pollValue.Effort.InverseAverage >= 1)
        result = `${pollValue.Effort.InverseAverage} - 4-Low - ${pollValue.Count} Vote(s)`;
    else if (pollValue.Effort.InverseAverage >= 0)
        result = `${pollValue.Effort.InverseAverage} - 5-Lowest - ${pollValue.Count} Vote(s)`;
    else
        result = "";
    return result;
}

function updateRecordCoD(workItem) {
    if (workItem != undefined) {
        if (workItem.Effort == undefined)
            workItem.Effort = 10123;
        if (workItem.BusinessValue == undefined)
            workItem.BusinessValue = 99999;
        if (workItem.TimeCriticality == undefined)
            workItem.TimeCriticality = 99999;
        if (workItem.RiskReductionMinusOpportunityEnablement == undefined)
            workItem.RiskReductionMinusOpportunityEnablement = 99999;
        workItem.CoD = workItem.RiskReductionMinusOpportunityEnablement + workItem.TimeCriticality + workItem.BusinessValue;
    }
}

function updateRecordOther(workItem, dataB, description) {
    workItem["State"] = getState(workItem["State"]);
    var priority = getPriority(workItem["WorkItemType"], workItem["Priority"]);
    workItem["PollValue"] = getPollValue(description, dataB[workItem.Id]);
    workItem["Priority"] = priority;
}

function updateRecordParent(parent, workItem) {
    if (parent == undefined) {
        workItem["ParentId"] = 9999999;
        workItem["ParentTitle"] = null;
        workItem["ParentState"] = null;
        workItem["ParentCoD"] = 9999999;
    }
    else {
        workItem["ParentId"] = parent["Id"];
        workItem["ParentCoD"] = parent["CoD"];
        workItem["ParentTitle"] = parent["Title"];
        workItem["ParentState"] = getState(parent["State"]);
    }
}

function getRecords(data, dataB, description) {
    var parent;
    var workItem;
    var records = [];
    for (var i = 0; i < data.length; i++) {
        parent = data[i].Parent;
        workItem = data[i].WorkItem;
        if (workItem.WorkItemType !== 'Feature')
            continue;
        if (workItem.State !== 'Active' && workItem.State !== 'New')
            continue;
        if (workItem.Tags != null && workItem.Tags.includes("Ignore"))
            continue;
        if ((window.location.href.indexOf('=LEO') > -1 && workItem.AreaPath !== 'ART SPS\\LEO') || (window.location.href.indexOf('=MES') > -1 && workItem.AreaPath !== 'ART SPS\\MES'))
            continue;
        updateRecordCoD(parent);
        updateRecordCoD(workItem);
        updateRecordParent(parent, workItem);
        updateRecordOther(workItem, dataB, description);
        records.push(workItem);
    }
    records.sort(compareFunction);
    return records;
}

function sendValue(element, page, id) {
    var body = { time: new Date().getTime(), id: id, page: page, value: element.value };
    $.post(_apiUrl + "save", body)
        .done(function (msg) {
            console.log("Posted value of " + element.value + " for " + id + " on page " + page + " " + msg);
        })
        .fail(function (xhr, textStatus, errorThrown) {
            alert(textStatus);
        });
}

function getFibonacciValue(average) {
    var result;
    if (average >= 7)
        result = 34;
    else if (average >= 6)
        result = 21;
    else if (average >= 5)
        result = 13;
    else if (average >= 4)
        result = 8;
    else if (average >= 3)
        result = 5;
    else if (average >= 2)
        result = 3;
    else if (average >= 1)
        result = 2;
    else if (average >= 0)
        result = 1;
    else
        result = "";
    return result;
}

function setRecords(workItems, page, description, th) {
    var record;
    var array = [];
    var count = "";
    var select = "";
    var average = "";
    var fibonacciValue = "";
    var html = "<tr><th>Parent Id</th><th>Parent Title</th><th>Id</th><th>Requester</th><th>Title</th><th>Assigned To</th><th>System(s)</th><th>State</th><th>Value</th><th>Poll Average</th><th>Fibonacci</th><th>Poll Description</th><th>Vote(s)</th><th>" + th + "</th><th>Up</th><th>Down</th></tr>";
    const element = document.getElementById("HeaderGrid");
    for (var i = 0; i < workItems.length; i++) {
        record = workItems[i];
        array = record.PollValue.split('-')
        average = array.length > 0 ? array[0] : "";
        fibonacciValue = getFibonacciValue(average);
        select = array.length > 2 ? array[1] + '-' + array[2] : "";
        count = array.length > 3 ? array[3].trim().split(' ')[0] : "";
        var length = record.Effort == undefined ? "" : record.Effort.toString().length;
        html += "<tr><td>" + '<a target="_blank" href="https://tfs.intra.infineon.com/tfs/FactoryIntegration/ART%20SPS/_workitems/edit/' + record.ParentId + '">' + record.ParentId + "</a>" +
            "</td><td>" + record.ParentTitle +
            "</td><td>" + '<a target="_blank" href="https://tfs.intra.infineon.com/tfs/FactoryIntegration/ART%20SPS/_workitems/edit/' + record.Id + '">' + record.Id + "</a>" +
            "</td><td>" + record.Requester +
            "</td><td>" + record.Title +
            "</td><td>" + record.AssignedTo +
            "</td><td>" + record.Tags +
            "</td><td>" + record.State +
            "</td><td>" +
            '<select onchange="sendValue(this, \'' + page + '\', ' + record.Id + ')">' +
            '<option value="9">Unknown</option>' +
            '<option value="1">Highest (Most ' + description + ')</option>' +
            '<option value="2">High</option>' +
            '<option value="3">Medium</option>' +
            '<option value="4">Low</option>' +
            '<option value="5">Lowest</option>' +
            "</select>" +
            "</td><td>" + average +
            "</td><td>" + fibonacciValue +
            "</td><td>" + select +
            "</td><td>" + count +
            "</td><td>" + length + " - " + record.Effort +
            "</td><td><a href='#' class='up'>Up</a>" +
            "</td><td><a href='#' class='down'>Down</a>" +
            "</td></tr>";
    }
    element.innerHTML = html.replaceAll(">null<", ">&nbsp;<");
}

function updateSite() {
    if (window.location.href.indexOf('=LEO') > -1) {
        document.title = document.title.replace("Infineon", "HiRel (Leominster)");
        document.getElementById("siteHeader").innerText = "HiRel (Leominster)";
    }
    else if (window.location.href.indexOf('=MES') > -1) {
        document.title = document.title.replace("Infineon", "Mesa");
        document.getElementById("siteHeader").innerText = "Mesa";
    }
    else {
        document.title = document.title.replace("Infineon", "Infineon");
        document.getElementById("siteHeader").innerText = "Infineon";
    }
}

function initIndex(url, apiUrl, page, description, th, urlB) {
    _apiUrl = apiUrl;
    updateSite();
    $.getJSON(urlB, { _: new Date().getTime() }, function (dataB) {
        $.getJSON(url, { _: new Date().getTime() }, function (data) {
            var records = getRecords(data, dataB, description);
            console.log(data.length);
            if (data.length > 0)
                console.log(data[0]);
            setRecords(records, page, description, th);
            $(".up,.down").click(function () {
                var row = $(this).parents("tr:first");
                if ($(this).is(".up")) {
                    row.insertBefore(row.prev());
                } else {
                    row.insertAfter(row.next());
                }
            });
        });
    });
    $("#HeaderGrid").on("dblclick", "tr", loadOne);
}