
function createContextLabelList(labels) {
    var result = document.createElement("ul");
    labels.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())).forEach(i => {
        var li = document.createElement("li");
        li.className = "badge badge-info";
        li.style.marginLeft = "5px";
        li.textContent = i;
        result.appendChild(li);
    });
    result.style.padding = 0;
    return result;
}

function createEventActionButtons(eventId) {
    var result = document.createDocumentFragment();
    var editLink = document.createElement("a");
    editLink.href = "event/edit?id=" +eventId;
    editLink.innerHTML = '<img alt="Edit" class="icon" src="public/img/note-outlined-symbol_icon-icons.com_73198.svg">';
    result.appendChild(editLink);

    var dupLink = document.createElement("a");
    dupLink.href = "event/add?from=" +eventId;
    dupLink.innerHTML = '<img alt="Duplicate" class="icon" src="public/img/copy-two-paper-sheets-interface-symbol_icon-icons.com_73283.svg">';
    result.appendChild(dupLink);

    var rmLink = document.createElement("a");
    rmLink.href = "event/delete?id=" +eventId;
    rmLink.innerHTML = '<img alt="Delete" class="icon" src="public/img/recycling-bin_icon-icons.com_73179.svg">';
    result.appendChild(rmLink);
    return result;
}

/**
 * @param {...(number|string|DocumentFragment|HTMLElement)} args
 */
function createTableRow(args) {
    var row = document.createElement("tr");
    for (var i =0, nbArgs = arguments.length; i < nbArgs; ++i) {
        var currentArg = arguments[i],
            col = document.createElement("td");

        if (currentArg instanceof DocumentFragment || currentArg instanceof HTMLElement) {
            col.appendChild(currentArg);
        } else {
            col.textContent = currentArg;
        }
        row.appendChild(col);
    }
    return row;
}

function createResultRow(tableId, dataObj) {
    var tableBody = document.getElementById(tableId),
        frag = document.createDocumentFragment(),
        data = [];

    tableBody.textContent = "";
    for (var i in dataObj)
        data.push([i, dataObj[i]]);
    data.sort((a, b) => b[1] -a[1]);
    data.forEach(i => {
        frag.appendChild(createTableRow(i[0], Math.round(i[1] *100) /100));
    });
    tableBody.appendChild(frag);
}

function displayEvents(events) {
    var eventTable = document.getElementById(htmlIds.tables.events),
        eventFrag = document.createDocumentFragment();
    var amountSum = {
        beneficiary: {},
        context: {},
        total: 0
    };
    eventTable.textContent = "";
    events.forEach(e => {
        eventFrag.appendChild(createTableRow(e["date"],
            e["label"],
            e["beneficiary"],
            createContextLabelList(e["context"]),
            e["amount"],
            createEventActionButtons(e["id"])));
        var amount = parseFloat(e["amount"]);
        amountSum.total += amount;
        amountSum.beneficiary[e["beneficiary"]] = (amountSum.beneficiary[e["beneficiary"]] || 0) +amount;
        e["context"].forEach(i => amountSum.context[i] = (amountSum.context[i] || 0) +amount);
    });
    var totalRow = createTableRow("Total", Math.round(amountSum.total * 100) /100, "");
    totalRow.children[0].colSpan = 4;
    eventFrag.appendChild(totalRow);
    eventTable.appendChild(eventFrag);

    createResultRow(htmlIds.tables.beneficiaries, amountSum.beneficiary);
    createResultRow(htmlIds.tables.contexts, amountSum.context);
}

function setPeriodStart(startDate) {
    var date = (new Date(startDate)).getTime(),
        eventFiltered = window["EVENTS"].filter(e => (new Date(e["date"])).getTime() >= date);
    displayEvents(eventFiltered);
}

var cachedPeriods = {};
function setPeriodId(id) {
    if (cachedPeriods[id]) {
        displayEvents(cachedPeriods[id]);
    } else {
        var get = new XMLHttpRequest();
        get.open("GET", "event/list?period=" +id, true);
        get.onreadystatechange = function() {
            if (get.readyState === XMLHttpRequest.DONE) {
                if (get.status === 200) {
                    var evts = cachedPeriods[id] = JSON.parse(get.responseText);
                    displayEvents(evts);
                }
            }
        };
        get.send(null);
    }
}

document.addEventListener("DOMContentLoaded", () => {
    if (window["PERIODS"].length)
        setPeriodStart(window["PERIODS"][0]["start"]);
});

window["setPeriodStart"] = setPeriodStart;
window["setPeriodId"] = setPeriodId;

