var clipboard;
$('html').on('host-page-loaded', function () {
    $('.inventory-report-btn').click(function () {
        // clear tmp local stored sql query to avoid inventory report loading from session storage
        sessionStorage.removeItem('inventory_sql');
        let el = $(this);
        window.open(
            encodeURI(el.data('url') + '&include=' + $('.host_id_SE').text().trim()),
            '_blank'
        );
    });

    $('body').on("pinned_loaded", function () {
        $("#pinned_items_wrapper").pinnedItems({data: pinnedItems});
    });

    loadPinnedItems();
    replacePinElements();

    const runReportCollection = (hostkey, lastReport) => {
        notify.info('Collecting report...');
        $('.request-report-collection')
            .hide()
            .attr('disabled', 'disabled')
            .html('<i class="icon-refresh white icon-spin"></i>')
            .fadeIn('slow');

        $.post('/actions/report_collection', {'hostkey': hostkey})
            .done(() => {
                let requestInProgress = false;
                // compare last report time and if changed reload the page
                const interval = setInterval(function () {
                    if (!requestInProgress) {
                        $.getJSON(`/host/info/${hostkey}`).then(function (result) {
                            if (result.lastreport > lastReport) {
                                notify.success('Report received.');
                                // wait 1 sec before page reloading
                                setTimeout(() => document.location.reload(), 1000);
                                clearInterval(interval);
                            }
                            requestInProgress = false;
                        });
                        requestInProgress = true;
                    }
                }, 2000);
            })
            .fail((error) => {
                notify.error(error.responseText);
            });
    };

    $('.request-report-collection').off().click(function () {
        // hide button and show spinner on click
        const lastReport = $(this).attr('data-last-report');
        const hostkey = $(this).attr('data-hostkey');
        runReportCollection(hostkey, lastReport);
    });
    $('.request-report-collection').removeAttr('disabled');

    $('.trigger-agent-run').off().click(function () {
        // hide button and show spinner on click
        $(this).attr('disabled', 'disabled');
        $('.request-report-collection').attr('disabled', 'disabled');
        notify.info('Triggering agent run...');

        const hostkey = $(this).attr('data-hostkey');
        const lastReport = $(this).attr('data-last-report');

        $.post('/actions/agent_run', {'hostkey': hostkey})
            .done(() => {
                notify.success('Agent run triggered.');
                $(this).removeAttr('disabled');
                // wait 2 sec before report collection
                setTimeout(() => runReportCollection(hostkey, lastReport), 2000);

            })
            .fail((error) => {
                notify.error(error.responseText);
                $(this).removeAttr('disabled');
            });
    });
    $('.trigger-agent-run').removeAttr('disabled');

    $("#remove-host-button").on("click", function(e){
        e.preventDefault();
        var target = $(this);
        var key = target.attr('key');
        var arrayKeys = [];
        arrayKeys.push(key);
        CF.Plugins.deleteHost.deleteHosts(arrayKeys);
    });

    if (clipboard != undefined) {
        clipboard.destroy();
    }
    clipboard = new ClipboardJS('#copy-host-link', {
        text: function () {
            return document.location.href;
        }
    });

    clipboard.on('success', function (e) {
        notify.success('Link copied.');
    });


    const ngAppEl = angular.element(document.querySelector('#ngApp'));
    if (!ngAppEl.injector()) { // when injector is true then app is already bootstrapped
        angular.bootstrap(ngAppEl, ['hostInfoApp']);
    }

    removeTooltipOnButtonClick();
});

let pinnedItems = [];

const pinItem = function (element) {
    $.post(MP_SITE_URL + "/pinItem/pin", {
        data: {type: element.getAttribute('pin-type'), name: element.getAttribute('pin-name')}
    }, function (data) {
        loadPinnedItems();
        notify.success('Pinned.');
        $(element).replaceWith(
            buildPinElement(true, element.getAttribute('pin-name'), element.getAttribute('pin-type'), data.id)
        );
    }, "json");
}

function unPinItem(element) {
    $.ajax({
        type: "DELETE",
        url: MP_SITE_URL + "/pinItem/pin/" + element.getAttribute('pin-id')
    }).done(function (response) {
        loadPinnedItems();
        notify.success('Unpinned.');

        $(element).replaceWith(
            buildPinElement(false, element.getAttribute('pin-name'), element.getAttribute('pin-type'))
        );
    });
}

function loadPinnedItems() {
    $.get(encodeURI(MP_SITE_URL + "/pinItem/pin?hostkey=" + $('.host_id_SE').text().trim()))
        .then(function (data) {
            pinnedItems = data;
            $('body').trigger("pinned_loaded");
        });
}

function replacePinElements() {
    $('.create-pin').each(function (index, element) {
        const name = $(element).attr('pin-name');
        const type = $(element).attr('pin-type');

        // if item pinned then show unpin element
        let pinnedItem = pinnedItems[type] != undefined ? pinnedItems[type].filter(item => item.name == name) : [];
        if (pinnedItem.length > 0) {
            $(element).replaceWith(buildPinElement(true, name, type, pinnedItem[0].id));
        } else {
            $(element).replaceWith(buildPinElement(false, name, type));
        }
    });
}

function buildPinElement(pinned, name, type, id = null) {
    let element;
    if (pinned === true) {
        element = `<i title="Click to remove from host info page"
                      class="bi bi-pin-fill blue unpin"
                      onclick="unPinItem(this)"
                      pin-id="${id}"
                      pin-name="${name}"
                      pin-type="${type}">
                   </i>`;

    } else {
        element = `<i title="Click to pin to host info page"
                      class="bi bi-pin-fill muted pin"
                      onclick="pinItem(this)"
                      pin-name="${name}"
                      pin-type="${type}" >
                   </i>`;
    }
    return element;
}

function processInventoryPin(attribute) {
    replacePinElements();
}

$.widget('ui.pinnedItems', {
    options: {
        data: {}
    },
    templates: {
        main: '<h4><i class="icon-pin"></i>Inventory</h4> <div class="pinned-container">%body%</div>',
        group: '<div> <h5>%Group_name%</h5> %items% <div class="muted" style="display: %display_no_pinned%">No %group_name% pinned</div> ' +
            '<button class="btn btn-blue-link show-%group_name% margin-top">Show all %group_name%</button> </div>',
        item: `<div class="row-fluid break-all">
                 <span class="muted span5">%item_name%:</span>
                 <span class="span7 break-all">
                 %item_value%
                 <i title="Click to remove from host info page"
                    class="bi bi-pin-fill blue unpin"
                    onclick="unPinItem(this)"
                    pin-id="%item_id%"
                    pin-name="%item_name%"
                    pin-type="%item_type%">
                 </i>
                 </span>
              </div>`,
    },

    _init: function () {
        this.element.html(this._buildHtml(this.options.data));
        $('.show-classes').click({type: 'classes'}, this.openModal);
        $('.show-variables').click({type: 'variables'}, this.openModal);
        $('.show-attributes').click({type: 'inventory'}, this.openModal);
    },


    openModal: function (event) {
        var userModalBody = {
            'header': '<h2>' + event.data.type.capitalizeFirstLetter() + ' defined on ' + $('.host_alias').text().trim().htmlSpecialChars() + '</h2>',
            'body_url': MP_SITE_URL + '/advancedreports/renderTable/' + event.data.type + '/' + $('.host_id_SE').text().trim()
        };
        const modal = $("<div></div>")
            .dialog_modal({
                passedArgs: ['', [], userModalBody],
                addBodyClass: 'form-buttons',
                css: {
                    'width': '80vw',
                    'margin-left': '-39vw'
                }
            })
            .data('ui-dialog_modal')
        const modalInstance = modal.instance()
        modalInstance.find('.modal-body').css('height', '70vh');
    },


    _getGroupName: function (name) {
        switch (name) {
            case 'class':
                name = 'classes';
                break;
            case 'variable':
                name = 'variables';
                break;
            case 'inventory':
                name = 'attributes';
                break;
            default:
                name = name.capitalizeFirstLetter()
        }
        return name;
    },

    _buildHtml: function (data) {
        let self = this;
        let html = this.templates.main;
        let groupsHtml = '';
        if (data !== undefined && Object.keys(data).length > 0) {
            Object.keys(data).forEach(function (group) {
                let groupHtml = self.templates.group
                    .replaceAll('%Group_name%', self._getGroupName(group).capitalizeFirstLetter())
                    .replaceAll('%group_name%', self._getGroupName(group))
                    .replace('%display_no_pinned%', data[group].length == 0 ? 'block' : 'none');
                let itemsHtml = '';
                data[group].forEach(function (item) {
                    let value;
                    switch (group) {
                        case 'class':
                            value = item.value === true ? 'Defined' : '<i class="grayed">(Not defined)</i>';
                            break;
                        case 'inventory':
                        case 'variable':
                            value = item.value === null ? '<i class="grayed">(Not reported)</i>' : item.value;
                            break;
                        default:
                            value = item.value;
                            break;
                    }
                    itemsHtml += self.templates.item
                        .replace('%item_name%', item.name)
                        .replace('%item_value%', value)
                        .replace('%item_id%', item.id);
                })
                groupHtml = groupHtml.replace('%items%', itemsHtml);
                groupsHtml += groupHtml;
            });
            return html.replace('%body%', groupsHtml);
        } else {
            return '';
        }
    }
});
