// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.

define(['fs/presenter/activity/ActivityTaskPresenter',
    'hp/view/NotificationDetailsView',
    'hp/core/StatusState',
    'hp/core/LinkTargetBuilder',
    'hp/core/NotificationFormatter',
    'hp/core/Localizer',
    'text!fsPages/activity/task_details.html',
    'jquery',
    'hp/lib/jquery.hpStatus',
    'hp/lib/jquery.hpTimestamp',
    'hp/lib/jquery.hpTextFormat',
    'hp/lib/jquery.hpProgressBar'],
function(presenter, notificationDetailsView, statusState, linkTargetBuilder, notificationFormatter,
    localizer, taskDetailsHtml) { "use strict";

    var ActivityTaskView = (function() {

        var PAGE = '#hp-activity-page';
        var DETAILS = '.hp-task-details';
        var SPINNER = '.hp-spinner';
        var SUB_TASK_TEMPLATE = '#hp-sub-task-template';
        var NOTIFICATION_CONTAINER = '.hp-task-notification-container';
        var TABLE_BODY = 'table tbody';

        /**
         * Constructor
         */
        function ActivityTaskView() {

            var detailsTemplate;
            var subTaskTemplate;
            var notificationDetailsTemplate;
            var layoutTimer = null;
            var renderDetailsCompletionHandler;

            function alignTableWidths(elem) {
                // align the details table columns with the outer table columns
                var container = elem.parents('.dataTables_wrapper');
                $('.dataTables_scrollHead thead td', container).each(function (index, elem2) {
                    $('thead td:eq(' + index + ')', elem).css('width', $(elem2).css('width'));
                });
            }

            function annotateRow(row, data) {
                var percent = data._notification.progress;
                var state = data._notification.state;
                if ('Skipped' === state || 'skipped' === state) {
                    percent = -1;
                }
                $('td .hp-duration', row).hpTimestamp();
                $('td .hp-progress', row).hpProgressBar(percent);
            }

            function renderState(data) {
                var result = '';
                var state = data._notification.state;
                var start, end;

                if ('running' === state.toLowerCase()) {
                    result += '<div class="hp-progress" style="width: 100px"></div>';
                }

                var str = "fs.activity.filter.state." + state.toLowerCase();
                result += '<span class="hp-secondary">' + localizer.getString(str) + '</span>';

                if (data._notification.endTimestamp) {
                    // don't show if duration is 0 seconds
                    start = Date.parseISOString(data._notification.timestamp);
                    end = Date.parseISOString(data._notification.endTimestamp);
                    if (start && end && (end.getTime() - start.getTime()) > 1000) {
                        result += '<span class="hp-duration">' +
                            data._notification.timestamp + '/' +
                            data._notification.endTimestamp + '</span>';
                    }
                }

                return result;
            }

            function addNotification(elem, task, depth) {
                var row, container = notificationDetailsTemplate.clone();
                var hasContent = notificationDetailsView.
                    update(container, task._notification, depth > 0);
                if (hasContent) {
                    row = $('<tr><td colspan="8"></td></tr>');
                    row.addClass('hp-task-details-messages-level-' + depth);
                    $('td', row).append(container);
                    $(TABLE_BODY, elem).append(row);
                }
            }

            function populateSubTasks(elem, treeNodes, depth) {
                var treeNode, task, row;
                var length = treeNodes.length;

                for (var i=0; i<length; i++) {
                    treeNode = treeNodes[i];
                    task = treeNode.resource;

                    // add this task
                    row = subTaskTemplate.clone();
                    row.addClass('hp-task-details-level-' + depth);

                    if (task.taskState && task.taskState.toLowerCase() === "running") {
                        $('td:eq(2) .hp-status', row).hpStatus("changing");
                    } else {
                        $('td:eq(2) .hp-status', row).hpStatus(statusState.getHealthStatus(task.taskState));
                    }

                    $('td:eq(2) .hp-name', row).text(task.name);
                    $('td:eq(3)', row).html(linkTargetBuilder.makeLink(
                        task.associatedResource.resourceName, task.associatedResource.resourceUri));
                    $('td:eq(4)', row).text(task.created).hpTimestamp();
                    $('td:eq(5)', row).html(renderState(task));
                    annotateRow(row, task);
                    //$('td:eq(6)', row).text(task.owner);
                    $(TABLE_BODY, elem).append(row);

                    addNotification(elem, task, depth);

                    // add it's children
                    populateSubTasks(elem, treeNode.children, depth + 1);
                }
            }

            function populateDetails(elem, tree) {
                var height;
                if (elem) {
                    $(elem).children().show();
                    $(SPINNER, elem).hide();
                    height = $(elem).height();
                    $(elem).css('min-height', height);
                    $(TABLE_BODY, elem).empty();
                    notificationDetailsView.update(
                        $(NOTIFICATION_CONTAINER, elem),
                        tree.resource._notification,
                        tree.children.length > 0);
                    populateSubTasks(elem, tree.children, 1);
                    alignTableWidths(elem);
                    $(elem).css('min-height', '');
                    $(elem).trigger('relayout');

                }
            }

            function layout() {
                $('.hp-task-details').each(function (index, elem) {
                    alignTableWidths($(elem));
                });
            }

            // Presenter events

            function onTaskChange(tree) {
                var elem = $(DETAILS + '[data-uri="' + tree.resource.uri + '"]');
                populateDetails(elem, tree);
                //let the table know that details were updated in case it needs to adjust the scroll position
                if (renderDetailsCompletionHandler) {
                    renderDetailsCompletionHandler(tree.resource.uri);
                }
            }

            // DOM events

            function onResize() {
                clearTimeout(layoutTimer);
                layoutTimer = setTimeout(layout, 50);
            }

            function registerListeners() {
                $(PAGE).on('relayout', layout);
                $(window).on('resize', onResize);
                presenter.on('taskChange', onTaskChange);
            }

            function unregisterListeners() {
                $(PAGE).off('relayout', layout);
                $(window).off('resize', onResize);
                presenter.off('taskChange', onTaskChange);
            }

            /**
             * @public
             */
            this.renderDetails = function (indexResult, oldDetails, handler) {
                var elem;
                var uri = indexResult.uri;

                // re-use old if we have it
                if (! oldDetails) {
                    elem = detailsTemplate.clone().attr('data-uri', uri);
                    $(elem).children().hide();
                    $(SPINNER, elem).show();
                    alignTableWidths(elem);
                }

                // even though the presenter is polling itself, get the latest so
                // we aren't too far out of sync
                presenter.expand(uri);
                renderDetailsCompletionHandler = handler;

                return elem;
            };

            this.collapsed = function (indexResult) {
                presenter.collapse(indexResult.uri);
            };

            this.pause = function () {
                unregisterListeners();
                presenter.pause();
            };

            this.resume = function () {
                registerListeners();
                presenter.resume();
            };

            this.init = function () {
                if (! detailsTemplate) {
                    detailsTemplate = $(taskDetailsHtml).filter('.hp-task-details');
                    localizer.localizeDom(detailsTemplate);
                    subTaskTemplate = $(SUB_TASK_TEMPLATE, detailsTemplate).remove().
                        removeAttr('id').removeClass('hp-template');
                    notificationDetailsTemplate =
                        $(NOTIFICATION_CONTAINER, detailsTemplate);
                }

                registerListeners();
            };

            // for ActivityView to build state cell
            this.renderState = renderState;

            this.annotateRow = annotateRow;
        }

        return new ActivityTaskView();
    }());

    return ActivityTaskView;
});

/// TBD:
/// details/resolution/actions content formatting

