/**
 * Created by leonidrom on 26/06/2017.
 */
const API_BASE_URL = "";
const SOLOMON_ALERTS_URL = "https://solomon.yandex-team.ru/admin/projects/webmaster/alerts/";
const GET_TRIGGERS_METHOD = "/trigger/list.json";
const GET_TRIGGERS_STATE_METHOD = "/alert/state.json";
const GET_PERIODIC_TASKS_TRIGGERS_STATE_METHOD = "/alert/periodicTasksState.json";

function secondsToHumanReadable(seconds) {
    console.info(seconds);

    const date = new Date(seconds * 1000);
    let str = '';
    const days = date.getUTCDate() - 1;
    if (days > 0) {
        str += days + 'd ';
    }

    const hours = date.getUTCHours();
    if (hours > 0) {
        str += hours + 'h ';
    }

    const mins = date.getUTCMinutes();
    if (mins > 0) {
        str += mins + 'm ';
    }

    if (days === 0 && hours === 0) {
        const seconds = date.getUTCSeconds();
        str += seconds + 's';
    }

    console.info(str);

    return str;
}


function getIdsByCategory(triggerIdsAndCategories) {
    let idsByCategory = new Map;
    let triggerIds = [];
    let i = 0;
    for (let trigger of triggerIdsAndCategories) {
        let id = trigger.id;
        let category = trigger.category;
        let ids = idsByCategory.get(category);
        if (!ids) {
            ids = [];
            idsByCategory.set(category, ids);
        }
        ids.push(id);
        triggerIds.push(id);
        if (++i > 20) {
            //break;
        }
    }

    return idsByCategory;
}

function addTriggerBlock($groupContent, id) {
    let $triggerBlock = $('<a class="trigger-block">').attr('id', id).attr('href', SOLOMON_ALERTS_URL + id);
    $triggerBlock.append($('<div class="name" />'));
    $triggerBlock.append($('<div class="value" />'));

    $groupContent.append($triggerBlock);

    return $triggerBlock;
}

function renderTriggers(triggerIdsAndCategories) {
    //triggerIdsAndCategories = triggerIdsAndCategories.slice(0, 3);
    console.log("Rendering " + triggerIdsAndCategories.length + " triggers");

    let idsByCategory = getIdsByCategory(triggerIdsAndCategories);

    // rendering group boxes
    for (let entry of idsByCategory) {
        let category = entry[0];
        let ids = entry[1];
        // calc width and height of group
        let length = ids.length;
        let totalRows = Math.floor(Math.sqrt(length));
        let totalColumns = Math.ceil(length / totalRows);
        let $groupContent = $("<div class='trigger-group-content'>")
            .css("display", "grid")
            .css("grid-template-columns", `repeat(${totalColumns}, 1fr)`);
        let $groupTitle = $("<div class='trigger-group-title'>").append(category);
        let $group = $("<div class='trigger-group'>").append($groupTitle).append($groupContent).appendTo($("#triggers"));
        // add triggers
        for (let id of ids) {
            addTriggerBlock($groupContent, id);
        }
    }

    //masonry
    $("#triggers").masonry({
        itemSelector: '.trigger-group',
        horizontalOrder: false,
        columnWidth: 35,
        fitWidth: true
    });

    loadTriggersState();
    setInterval(loadTriggersState, 60000);
}

function updateTriggerState($triggerBlock, annotations, isDataAge) {
    $triggerBlock.removeClass('red yellow green').addClass(annotations['trafficLight.color']);
    $triggerBlock.attr('title', annotations['name']);

    let children = $triggerBlock.children();
    children[0].textContent = annotations['name'];

    let val = annotations['trafficLight.value'];
    if (isDataAge) {
        val = secondsToHumanReadable(val);
    }

    children[1].textContent = val;
}

function updateTriggersState(statuses) {
    for (let id in statuses) {
        if (statuses.hasOwnProperty(id)) {
            let $triggerBlock = $('#' + id);
            let annotations = statuses[id]['annotations'];
            let isDataAge = annotations['name'].includes('Data age');

            updateTriggerState($triggerBlock, annotations, isDataAge);
        }
    }
}

function updatePeriodicTasksTriggersState(statuses) {
    $groupContent = $('#periodicTasksTriggers > .trigger-group > .trigger-group-content');
    $groupContent.empty();

    for (let id in statuses) {
        if (statuses.hasOwnProperty(id)) {
            let $triggerBlock = addTriggerBlock($groupContent, id);
            let annotations = statuses[id]['annotations'];

            updateTriggerState($triggerBlock, annotations, true);
        }
    }
}


function loadTriggers(filter) {
    console.info("Loading triggers list");
    $.ajax({
        url: API_BASE_URL + GET_TRIGGERS_METHOD,
        crossDomain: true,
        success: function (d) {
            if (d.status === "SUCCESS") {
                if (filter && typeof (filter) === 'function') {
                    const triggers = [];
                    for (let t of d.data.triggerCategories) {
                        if (filter(t)) {
                            triggers.push(t);
                        }
                    }
                    renderTriggers(triggers);
                } else {
                    renderTriggers(d.data.triggerCategories);
                }
            } else {
                console.error("Error: " + d.errors[0].message);
            }
        }
    });
}

function loadTriggersState() {
    console.info("Loading triggers state");
    $.ajax({
        url: API_BASE_URL + GET_TRIGGERS_STATE_METHOD,
        crossDomain: true,
        success: function (d) {
            if (d.status === "SUCCESS") {
                updateTriggersState(d.data.statuses);

            } else {
                console.error("Error: " + d.errors[0].message);
            }
        }
    });

    $.ajax({
        url: API_BASE_URL + GET_PERIODIC_TASKS_TRIGGERS_STATE_METHOD,
        crossDomain: true,
        success: function (d) {
            if (d.status === "SUCCESS") {
                updatePeriodicTasksTriggersState(d.data.statuses);
            } else {
                console.error("Error: " + d.errors[0].message);
            }
        }
    });
}
