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

define(['hpsum/presenter/type/TypePresenter',
    'hpsum/presenter/activity/ActivityPresenter',
    'hp/core/LinkTargetBuilder',
    'hp/core/Localizer',
    'jquery', 'modernizr',
    'hp/lib/jquery.dropDownMenu',
    'hp/lib/jquery.hpPanels',
    'lib/jquery.ThreeDots',
    'lib/jquery.dateFormat',
    'lib/jquery.columnizer',
    'hp/lib/date',
    'hp/lib/jquery.hpSimpleSelect'],
function(presenter, ActivityPresenter, linkTargetBuilder, localizer) { "use strict";

    var TypeShowActivityView = (function() {
      
        var TABLE = '#tour-activity';
        var TABLE_WRAPPER = '#tour-activity';
        var BODY = '#hp-body-div';
        
        var USERS = ['no one', 'Sam', 'Wilma', 'Fred'];
      
        /**
         * Constructor
         */
        function TypeShowActivityView() {
          
            var activityPresenter = new ActivityPresenter();
            
            // TODO: too much duplication with activity/ActivityView.js, refactor
            var dataTable;
            var detailsTemplate;
            
            function onActivitySelectionChange(selection) {
                $('.hp-header-selection').
                    html((selection.uris ? selection.uris.length : 0) + ' selected');
                    
                $(dataTable.fnSettings().aoData).each(function() {
                    $(this.nTr).removeClass('hp-selected');
                });
                if (selection.uris) {
                    var aTrs = $(TABLE + ' tbody tr');
                    $.each(aTrs, function() {
                        var tr = this;
                        var indexResult = dataTable.fnGetData(tr);
                        if ((indexResult) &&
                            ($.inArray(indexResult.uri, selection.uris) != -1)) {
                            $(tr).addClass('hp-selected');
                        }
                    });
                }
            }
            
            function clickRow(ev) {
                var indexResult = dataTable.fnGetData(this);
                var uri = indexResult.uri;
                if (ev.metaKey || ev.ctrlKey) {
                    activityPresenter.toggleSelectedUri(uri, false);
                } else if (ev.shiftKey) {
                    /* TODO:
                    var firstIndex = $('.hp-alert-selected').first().index();
                    var lastIndex = alert.index();
                    if (firstIndex > lastIndex) {
                        var tmp = firstIndex;
                        firstIndex = lastIndex;
                        lastIndex = tmp;
                    }
                    var alerts = $('.hp-alert:gt(' + (firstIndex - 1) + ')' +
                        ':lt(' + (lastIndex - firstIndex + 1) + ')');
                    var uris = alerts.map(function () {
                        return $(this).attr('data-hp-alert-uri');
                    }).get();
                    presenter.setSelectedUris(uris);
                    */
                } else {
                    activityPresenter.setSelectedUris([uri]);
                }
            }
            
            function onIndexResultsChange(indexResults) {
                $('.hp-activity-title').html(indexResults.count + ' Messages');
                dataTable.fnClearTable(indexResults.members.length === 0);
                var rowCount = dataTable.fnAddData(indexResults.members).length;
                
                $(TABLE + ' tbody tr').click(clickRow);
            }
            
            function calculateTableHeight() {
                var parent = $(TABLE_WRAPPER).parent();
                if ($(TABLE_WRAPPER).length === 0) {
                    parent = $(TABLE).parent();
                }
                return parent.height() - 
                    ($(TABLE).offset().top - parent.offset().top) -
                    $(TABLE + ' thead').height();
            }
            
            function onResize() {
                $(TABLE).css('width', '');
                var oSettings = dataTable.fnSettings();
                oSettings.oScroll.sY = calculateTableHeight();
                $(TABLE_WRAPPER + ' .dataTables_scrollBody').css('height', oSettings.oScroll.sY);
                dataTable.fnAdjustColumnSizing();
            }
            
            function initTable() {
                var options = {
                    bPaginate : false,
                    bFilter : false,
                    bInfo : false,
                    bDeferRender : true,
                    //bScrollInfinite : true, // use extras/Scroller
                    //sScrollY : calculateTableHeight(),
                    //sScrollX : '100%',
                    //bAutoWidth : true,
                    aaData : [],
                    aoColumns : [
                        // expand/collapse
                        {fnRender: function (oObj) {
                            return '<div class="hp-collapser"></div>';
                          },
                          sWidth: 20, sClass: "hp-icon"},
                        // status
                        {fnRender: function (oObj) {
                            return '<div class="hp-status">' + oObj.aData.status +
                                (oObj.aData.changing ? ' *' : '') + '</div>';
                          },
                          sWidth: 20, sClass: "hp-icon"},
                        // progress
                        {fnRender: function (oObj) {
                            if (oObj.aData.category === 'task') {
                                return '<span class="hp-progress hp-condensed">' +
                                '</span>' + oObj.aData.progress + '%';
                            } else {
                                return '';
                            }
                          },
                          sWidth: 100},
                        // message
                        {fnRender: function (oObj) {
                            if (oObj.aData.category === 'alert') {
                                return oObj.aData.name;
                            } else if (oObj.aData.category === 'task') {
                                return oObj.aData.name + ' - ' +
                                    oObj.aData.progressStep;
                            } else {
                                return oObj.aData.category;
                            }
                        }},
                        // date/time
                        {fnRender: function (oObj) {
                            // 2011-12-20T08:48:22.888Z
                            var date = Date.parseISOString(oObj.aData.date);
                            var formattedDate;
                            if (date.isToday()) {
                                formattedDate = localizer.getString('hpsum.task.today');
                            } else if (date.getFullYear() === (new Date()).getFullYear()) {
                                formattedDate = $.format.date(date, 'MMM d');
                            } else {
                                formattedDate = $.format.date(date, 'M/d/yy');
                            }
                            return '<div class="hp-timestamp">' +
                                formattedDate + ' ' + $.format.date(
                                    Date.parseISOString(oObj.aData.date), 'h:mma') +
                                '</div>';
                          },
                          sWidth: '10%'},
                        // notes
                        {fnRender: function (oObj) {
                            if (oObj.aData.notes.length > 0) {
                                return '<div class="hp-numeric">' + 
                                    oObj.aData.notes.length + '</div>';
                            } else {
                                return '';
                            }
                          },
                          sWidth: 20, sClass: "hp-icon"},
                        // initiator
                        {fnRender: function (oObj) {
                            return '<div class="tour-owner">' +
                                '<div class="hp-value">' +
                                (oObj.aData.owner ? oObj.aData.owner : 'no one') +
                                '</div></div>';
                          },
                          sWidth: '7%'}
                    ],
                    aaSorting: [[ 4, "desc" ]],
                    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                        $('td:eq(1) > div.hp-status', nRow).hpStatus();
                        if (aData.category === 'task') {
                            $('td:eq(2) span', nRow).hpProgressBar(aData.progress);
                        }
                        return nRow;
                    }
                };
                
                dataTable = $(TABLE).dataTable(options);
            }
          
            function onSelectionChange(selection) {
                activityPresenter.setSourceUris(selection.uris);
            }
          
            /**
             * @public
             */
            this.resume = function() {
                activityPresenter.on('indexResultsChange', onIndexResultsChange);
                activityPresenter.on("selectionChange", onActivitySelectionChange);
                presenter.on("selectionChange", onSelectionChange);
                $(window).bind('resize', onResize);
                
                // Add actions to details actions menu
                $('.hp-details-actions-menu').
                    append('<li class="tour-alert-action"><a>Clear alerts</a></li>');
            };
            
            this.pause = function() {
                activityPresenter.off('indexResultsChange', onIndexResultsChange);
                activityPresenter.off("selectionChange", onActivitySelectionChange);
                presenter.off("selectionChange", onSelectionChange);
                $(window).unbind('resize', onResize);
                // Remove actions to details actions menu
                $('.hp-details-actions-menu .tour-alert-action').remove();
            };
            
            this.init = function() {
                activityPresenter.init();
                
                initTable();
                
                this.resume();
            };
        }

        return new TypeShowActivityView();
    }());
    
    return TypeShowActivityView;
});
