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

define(['hpsum/presenter/type/TypePresenter',
    'hpsum/presenter/alerts/AlertsPresenter',
    '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, AlertsPresenter, linkTargetBuilder, localizer) { "use strict";

    var TypeShowAlertsView = (function() {
      
        var TABLE = '#tour-alerts';
        var TABLE_WRAPPER = '#tour-alerts_wrapper';
        var DETAILS_TEMPLATE = '#tour-alert-details-template';
        var BODY = '#hp-body-div';
        
        var USERS = ['no one', 'Sam', 'Wilma', 'Fred'];
      
        /**
         * Constructor
         */
        function TypeShowAlertsView() {
          
            var alertsPresenter = new AlertsPresenter();
            
            // TODO: too much duplication with alerts/AlertsView.js, refactor
            var dataTable;
            var detailsTemplate;
            
            function stateChange(indexResult) {
                alertsPresenter.toggleState(indexResult.uri);
            }
            
            function appendNote(details, alertNote) {
                var note = $('.hp-comment.hp-template', details).clone();
                note.removeClass('hp-template');
                var date = Date.parseISOString(alertNote.date);
                $('.hp-comment-user', note).html(alertNote.user);
                $('.hp-comment-text', note).html(alertNote.text);
                if (date.isToday()) {
                    $('.hp-timestamp', note).html($.format.date(date, 'h:mma'));
                    $('.hp-timestamp', note).
                        append($('<span class="hp-date-annotate">(<span class="timeago" title="' +
                            alertNote.date + '"></span>)</span>'));
                    $('.hp-timestamp .timeago', note).timeago();
                } else if (date.getFullYear() === (new Date()).getFullYear()) {
                    $('.hp-timestamp', note).html($.format.date(date, 'MMM d h:mma'));
                } else {
                    $('.hp-timestamp', note).html($.format.date(date, 'M/d/yy h:mma'));
                }
                note.show();
                $('.hp-comments', details).append(note);
                
                $('.hp-comment-delete', note).click(function () {
                    alert("TBD");
                });
            }
            
            function addNote(details, alertUri) {
                var alertNote = {user: 'Sam',
                    text: $('.hp-comment-form-text', details).val(),
                    date: new Date().toISOString()};
                alertsPresenter.addNote(alertUri, alertNote);
                appendNote(details, alertNote);
                $('.hp-comment-form-text', details).val('')
            }
            
            function generateDetails(alertRow) {
                var indexResult = dataTable.fnGetData(alertRow[0]);
                var details = detailsTemplate.clone();
                
                $.each(indexResult.notes, function (index, alertNote) {
                    appendNote(details, alertNote);
                });
                
                $('.hp-comment-form-text', details).focus(function () {
                    $('.hp-comment-add', details).fadeIn();
                });
                
                $('.hp-comment-form-text', details).bind('keydown', function (ev) {
                    if (13 === ev.keyCode) {
                        addNote(details, indexResult.uri);
                        ev.preventDefault();
                    }
                });
                
                $('.hp-comment-add', details).bind('click', function () {
                    addNote(details, indexResult.uri);
                });
                
                return details;
            }
            
            function expandAlert(alertRow) {
                if (! $('.hp-collapser', alertRow).hasClass('hp-active')) {
                    $('.hp-collapser', alertRow).addClass('hp-active');
                    alertRow.addClass('hp-expanded');
                    var details = generateDetails(alertRow);
                    dataTable.fnOpen(alertRow[0], details[0], 'hp-row-details-cell' );
                    details.slideDown(400);
                }
            }
            
            function collapseAlert(alertRow) {
                if ($('.hp-collapser', alertRow).hasClass('hp-active')) {
                    $('.hp-collapser', alertRow).removeClass('hp-active');
                    $('.hp-row-details', alertRow.next()).slideUp(400, function () {
                        alertRow.removeClass('hp-expanded');
                        dataTable.fnClose(alertRow[0]);
                    });
                }
            }
            
            function toggleExpansion(alertRow) {
                if (alertRow.hasClass('hp-expanded')) {
                    collapseAlert(alertRow);
                } else {
                    expandAlert(alertRow);
                }
            }
            
            function onAlertsSelectionChange(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');
                        } else {
                            collapseAlert($(tr));
                        }
                    });
                }
            }
            
            function clickRow(ev) {
                var indexResult = dataTable.fnGetData(this);
                var uri = indexResult.uri;
                if (ev.metaKey || ev.ctrlKey) {
                    alertsPresenter.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 {
                    alertsPresenter.setSelectedUris([uri]);
                }
            }
            
            function onIndexResultsChange(indexResults) {
                $('.hp-alerts-title').html(indexResults.count + ' Alerts');
                dataTable.fnClearTable(indexResults.members.length === 0);
                var rowCount = dataTable.fnAddData(indexResults.members).length;
                
                $(TABLE + ' .hp-collapser').click(function (ev) {
                    toggleExpansion($(this).parents('tr'));
                });
                $(TABLE + ' .hp-comments-summary').click(function (ev) {
                    toggleExpansion($(this).parents('tr'));
                });
                
                $(TABLE + ' tbody tr').click(clickRow);
                $(TABLE + ' .hp-alert-state-change').click(function (ev) {
                    var indexResult = dataTable.fnGetData($(this).parents('tr')[0]);
                    stateChange(indexResult);
                    ev.stopPropagation();
                });
                
                $(TABLE + ' .tour-assignment').bind('change', function (ev, value) {
                    //console.log("!!! assignment changed to " + value);
                    var indexResult = dataTable.fnGetData($(this).parents('tr')[0]);
                    if ('no one' === value) {
                        value = null;
                    }
                    alertsPresenter.assignAlert(indexResult.uri, value);
                });
            }
            
            function calculateTableHeight() {
                var parent = $(TABLE_WRAPPER).parent();
                if ($(TABLE_WRAPPER).length === 0) {
                    parent = $(TABLE).parent();
                }
                //console.log("!!! parent height: " + parent.height() + " top: " + parent.offset().top);
                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();
                //console.log("!!! height to " + oSettings.oScroll.sY);
                $(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"},
                        // 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%'},
                        // status
                        {fnRender: function (oObj) {
                            return '<div class="hp-status">' + oObj.aData.status +
                                (oObj.aData.changing ? ' *' : '') +
                              '</div>';},
                          sWidth: 20, sClass: "hp-icon"},
                        // text
                        {mDataProp: "name"},
                        // category
                        {mDataProp: "category", sWidth: '5%'},
                        // notes
                        {fnRender: function (oObj) {
                          if (oObj.aData.notes.length > 0) {
                              return '<div class="hp-comments-summary"><span>' +
                                  oObj.aData.notes.length + '</span></div>';
                          } else {
                              return '<div class="hp-comments-summary hp-empty"></div>';
                          }},
                          sWidth: 20, sClass: "hp-icon"},
                        // assignment
                        {fnRender: function (oObj) {
                            return '<div class="tour-assignment">' +
                                (oObj.aData.owner ? oObj.aData.owner : 'no one') +
                                '</div>';
                          },
                          sWidth: '5%'},
                        // state
                        {fnRender: function (oObj) {
                            return '<div class="hp-reveal-control">' +
                                '<span class="hp-value">' + oObj.aData.state +
                                '</span>' +
                                '<a class="hp-alert-state-change hp-control">' +
                                ('active' === oObj.aData.state ? 'Clear' : 'Restore') +
                                '</a>';},
                          sWidth: '5%'}
                    ],
                    aaSorting: [[ 1, "desc" ]],
                    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                        $('td:eq(2) > div.hp-status', nRow).hpStatus();
                        $('td:eq(6) div.tour-assignment', nRow).hpSimpleSelect(USERS);
                        return nRow;
                    }
                };
                
                dataTable = $(TABLE).dataTable(options);
                
                detailsTemplate = $(DETAILS_TEMPLATE).removeAttr('id').detach();
            }
          
            function onSelectionChange(selection) {
                alertsPresenter.setFilterProperties({sourceUri: selection.uris});
            }
          
            /**
             * @public
             */
            this.resume = function() {
                alertsPresenter.on('indexResultsChange', onIndexResultsChange);
                alertsPresenter.on("selectionChange", onAlertsSelectionChange);
                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() {
                alertsPresenter.off('indexResultsChange', onIndexResultsChange);
                alertsPresenter.off("selectionChange", onAlertsSelectionChange);
                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() {
                alertsPresenter.init();
                
                initTable();
                
                this.resume();
            };
        }

        return new TypeShowAlertsView();
    }());
    
    return TypeShowAlertsView;
});
