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

define(['hpsum/model/alert/AlertResource',
    'hpsum/presenter/alerts/AlertsPresenter',
    'hp/core/LinkTargetBuilder',
    'hp/core/Localizer',
    'jquery',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpStatus',
    'lib/jquery.dateFormat',
    'hp/lib/date',
    'hp/lib/jquery.hpDropMenu',
    'hp/lib/jquery.hpSelect'],
function(resource, Presenter, linkTargetBuilder, localizer) { "use strict";

    var AlertsView = (function() {
      
        var PAGE = '#tour-alerts-page';
        var FILTERBAR_CONTROL = PAGE + ' .hp-filterbar-control';
        var FILTER = '#hp-alert-filter';
        var DATE_FILTER = '#hp-alert-date-filter';
        var DATE_MENU = '#hp-alert-date-menu';
        var TABLE = '#tour-alerts';
        var TABLE_WRAPPER = '#tour-alerts_wrapper';
        var DETAILS_TEMPLATE = '#tour-alert-details-template';
        var BODY = '#hp-body-div';
        var FILTERBAR = '.hp-master-filter';
        var FILTERBAR_OPEN = 'hp-filterbar-open';
        
        var USERS = ['no one', 'Sam', 'Wilma', 'Fred'];
      
        /**
         * Constructor
         */
        function AlertsView() {
          
            var presenter = new Presenter();
            var dataTable;
            var detailsTemplate;
            
            function resizeTable() {
                // we delay so any CSS animation can finish
                setTimeout(function () {dataTable.fnAdjustColumnSizing();}, 500);
            }
            
            function closeFilterbar() {
                $('.hp-sub-nav').append(
                    $(FILTERBAR + ' .hp-filter').removeClass('hp-active hp-pinned'));
                $(PAGE).removeClass(FILTERBAR_OPEN);
                resizeTable();
            }

            function openFilterbar() {
                $(FILTERBAR).append(
                    $('.hp-sub-nav .hp-filter').addClass('hp-active hp-pinned'));
                $(PAGE).addClass(FILTERBAR_OPEN);
                resizeTable();
            }
            
            function toggleFilterbar() {
                if (! $(PAGE).hasClass(FILTERBAR_OPEN)) {
                    openFilterbar();
                } else {
                    closeFilterbar();
                }
            }
            
            function stateChange(indexResult) {
                presenter.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()};
                presenter.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 onSelectionChange(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) {
                    presenter.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 {
                    presenter.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) {
                    var indexResult = dataTable.fnGetData($(this).parents('tr')[0]);
                    if ('no one' === value) {
                        value = null;
                    }
                    presenter.assignAlert(indexResult.uri, value);
                });
            }
            
            function searchFocused() {
                $('#hp-search').removeClass('hp-active');
            }
            
            function searchChanged() {
                presenter.setFilterSearch($('#hp-search input').val());
            }
            
            function selectAll() {
                presenter.selectAll();
            }
            
            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').outerHeight();
            }
            
            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 onFilterChange(ev, values) {
                presenter.setFilterProperties(values);
                $(FILTER + ' .hp-value').text(presenter.getFilterSummary());
            }
            
            function onDateFilterChange(ev, values) {
                
            }
            
            function initFilters() {
              
                $(FILTER).hpSelect({multiSelect: true}).change(onFilterChange);
                
                $('#hp-alert-filter-default').bind('click', function (ev) {
                    presenter.setDefaultFilterProperties();
                });
                
                $(DATE_FILTER).hpSelect().change(onDateFilterChange);
                
                /*$(DATE_MENU + ' li').bind('click', function (ev) {
                    $(DATE_MENU + ' li').removeClass('hp-alert-date-selected');
                    $(this).addClass('hp-alert-date-selected');
                    if ($('#hp-alert-date-range').hasClass('hp-alert-date-selected')) {
                        $('#hp-alert-date-range-form').slideDown();
                    } else {
                        $('#hp-alert-date-range-form').slideUp();
                    }
                    $('#hp-alert-date-control').html(
                        $(DATE_MENU + ' li.hp-alert-date-selected').
                            map(function () {return $.trim($(this).text());}).
                            get().join(', '));
                    ev.stopPropagation();
                });*/
                
                $('#hp-alert-date-range-from').datepicker();
                $('#hp-alert-date-range-to').datepicker();
                
                $(FILTERBAR_CONTROL).bind('click', toggleFilterbar);
            }
            
            function initActions() {
                $('#tour-alerts-actions').hpDropMenu();
                
                $('.hp-header-select-all').click(selectAll);
                
                $('#tour-alert-dismiss').click(function () {
                    presenter.dismissSelected();
                });
                
                $('#tour-alert-delete').click(function () {
                    presenter.deleteSelectedItems({});
                });
            }
            
            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},
                        // status
                        {fnRender: function (oObj) {
                            return '<div class="hp-status">' + oObj.aData.status +
                                (oObj.aData.changing ? ' *' : '') +
                              '</div>';},
                          sWidth: 20, sClass: "hp-icon"},
                        // text
                        {mDataProp: "name"},
                        // source
                        {fnRender: function (oObj) {
                            return linkTargetBuilder.makeLink(oObj.aData.sourceName,
                                oObj.aData.sourceUri);},
                          sWidth: '15%'},
                        // 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},
                        // category
                        {mDataProp: "alertCategory", sWidth: '5%'},
                        // assignment
                        {fnRender: function (oObj) {
                            return '<div class="tour-assignment">' +
                                '<div class="hp-value">' +
                                (oObj.aData.owner ? oObj.aData.owner : 'no one') +
                                '</div></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: [[ 4, "desc" ]],
                    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                        $('td:eq(1) > div.hp-status', nRow).hpStatus();
                        $('td:eq(7) div.tour-assignment', nRow).hpSelect({options: USERS, label: 'Assignment'});
                        return nRow;
                    }
                };
                
                dataTable = $(TABLE).dataTable(options);
                
                detailsTemplate = $(DETAILS_TEMPLATE).removeAttr('id').detach();
            }
            
            /**
             * @public
             */
            this.pause = function () {
                $('#hp-search input').unbind('focus', searchFocused);
                $('#hp-search input').unbind('keyup', searchChanged);
                presenter.off('indexResultsChange', onIndexResultsChange);
                presenter.off('selectionChange', onSelectionChange);
                $(window).unbind('resize', onResize);
            };
            
            this.resume = function () {
                document.title = 'Alerts';
                $('#hp-search input').bind('focus', searchFocused);
                $('#hp-search input').bind('keyup', searchChanged);
                searchChanged();
                presenter.on('indexResultsChange', onIndexResultsChange);
                presenter.on('selectionChange', onSelectionChange);
                $(window).bind('resize', onResize);
            };
            
            this.init = function() {
                
                presenter.init();
                
                initFilters();
                initActions();
                initTable();
                
                this.resume();
            };
        }

        return new AlertsView();
    }());
    
    return AlertsView;
});
