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

define(['hpsum/model/activity/ActivityResource',
    'hpsum/presenter/activity/ActivityPresenter',
    'hp/view/MasterPaneView',
    'hp/core/LinkTargetBuilder',
    'hp/core/Localizer',
    'jquery',
    'lib/jquery.dataTables',
    'hp/lib/jquery.hpStatus',
    'hp/lib/jquery.hpTimestamp',
    'hp/lib/date',
    'hp/lib/jquery.hpSelect',
    'hp/lib/jquery.hpProgressBar'],
function(resource, Presenter, MasterPaneView, linkTargetBuilder, localizer) { "use strict";

    var ActivityResourceView = (function() {
      
        var TYPE = 'activity';
        var DETAILS_TEMPLATE = '#tour-activity-details-template';
        var CATEGORY_FILTER = '#hp-activity-category-filter';
        var STATE_FILTER = '#hp-activity-state-filter';
        var DATE_FILTER = '#hp-activity-date-filter';
      
        /**
         * Constructor
         */
        function ActivityResourceView() {
          
            var presenter = new Presenter();
            var masterPaneView = new MasterPaneView();
            var detailsTemplate = null;
            var context = null;
            
            function appendNote(details, activityNote) {
                var note = $('.hp-comment.hp-template', details).clone();
                note.removeClass('hp-template');
                $('.hp-comment-user', note).html(activityNote.user);
                $('.hp-comment-text', note).html(activityNote.text);
                $('.hp-timestamp', note).text(activityNote.date).hpTimestamp();
                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 renderDetails(indexResult) {
                var details = detailsTemplate.clone();
                
                if (indexResult.hasOwnProperty('notes')) {
                    $.each(indexResult.notes, function (index, activityNote) {
                        appendNote(details, activityNote);
                    });
                }
                
                $('.hp-comment-form-text', details).focus(function () {
                    $('.hp-comment-add', details).fadeIn();
                }).blur(function () {
                    $('.hp-comment-add', details).fadeOut();
                });
                
                $('.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 onSelectionChange(selection) {
            }
            
            function onIndexResultsChange(indexResults) {
            }
            
            function onFilterChange(filter) {
                $(STATE_FILTER).hpSelect('set', presenter.getStateFilter());
                $(STATE_FILTER + ' .hp-value').
                    text(presenter.getStateFilterSummary());
            }
            
            function onStateFilterChange(ev, values) {
                presenter.setStateFilter(values);
            }
            
            function initTable() {
                detailsTemplate = $('#tour-activity-details-template').
                    remove().attr('id', '').removeClass('hp-template');
                    
                var routeContext = presenter.getRouteContext();
                var tableId = 'tour-' + routeContext + '-activities';
                $('#tour-activities').attr('id', tableId);
                    
                masterPaneView.init({
                    resource: resource,
                    pane: $('#tour-activity-pane .hp-details-contents'),
                    table: $('#' + tableId),
                    multiSelect: true,
                    dataTableOptions:  {
                        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", mDataProp: 'status'},
                            // message
                            {fnRender: function (oObj) {
                                if (oObj.aData.category === 'alert') {
                                    return oObj.aData.name;
                                } else if (oObj.aData.category === 'task') {
                                    return oObj.aData.name
                                } else {
                                    return oObj.aData.category;
                                }
                            }, mDataProp: 'name'},
                            // progress
                            {fnRender: function (oObj) {
                                if (oObj.aData.category === 'task' &&
                                    'finished' !== oObj.aData.state) {
                                    var progress = oObj.aData.progress;
                                    if (! progress) {
                                        progress = 0;
                                    }
                                    return '<span data-percent="' + progress +
                                        '" class="hp-progress hp-condensed">' +
                                        '</span>' + progress + '%';
                                } else {
                                    return '';
                                }
                              },
                              sWidth: 90, mDataProp: 'progress'},
                            // 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/280\
                                    ');
                                }
                                return '<div class="hp-timestamp">' +
                                    formattedDate + ' ' + $.format.date(
                                        Date.parseISOString(oObj.aData.date), 'h:mma') +
                                    '</div>';
                              },
                              sWidth: 90, mDataProp: 'date'},
                            // type
                            {mDataProp: 'category', sClass: "hp-secondary", sWidth: 50},
                            // state
                            {mDataProp: 'state', sClass: "hp-secondary", sWidth: 50},
                            // notes
                            {fnRender: function (oObj) {
                                if (oObj.aData.notes && oObj.aData.notes.length > 0) {
                                    return oObj.aData.notes.length;
                                } else {
                                    return '';
                                }
                              },
                              sWidth: 20, sClass: "hp-numeric"},
                            // initiator
                            {fnRender: function (oObj) {
                                var result = '<div class="tour-owner">';
                                if (oObj.aData.owner) {
                                    result += '<div class="hp-value">' +
                                        oObj.aData.owner + '</div>';
                                } else {
                                    result += '<div class="hp-unset">no one</div>';
                                }
                                result += '</div>';
                                return result;
                              },
                              sWidth: '7%', mDataProp: 'owner'}
                        ],
                        aaSorting: [[ 4, "desc" ]],
                        fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                            $('td:eq(1) > div.hp-status', nRow).hpStatus();
                            if (aData.category === 'task' &&
                                'finished' !== aData.state) {
                                $('td:eq(3) span', nRow).hpProgressBar();
                            }
                            return nRow;
                        }
                    },
                    detailsRenderer: renderDetails
                });
            }
            
            /**
             * @public
             */
            this.pause = function () {
                presenter.off('indexResultsChange', onIndexResultsChange);
                presenter.off('selectionChange', onSelectionChange);
                presenter.off('filterChange', onFilterChange);
                $('.hp-details-show-section').removeClass('hp-notify-disabled');
                presenter.pause();
                masterPaneView.pause();
                // remove actions
                $('#tour-activity-actions').hide();
            };
            
            this.resume = function () {
                presenter.on('indexResultsChange', onIndexResultsChange);
                presenter.on('selectionChange', onSelectionChange);
                presenter.on('filterChange', onFilterChange);
                $('.hp-details-show-section').addClass('hp-notify-disabled');
                presenter.resume();
                masterPaneView.resume();
                // add actions
                $('#tour-activity-actions').show();
                onFilterChange(resource.getIndexFilter());
            };
            
            this.init = function() {
              
                $(STATE_FILTER).hpSelect({multiSelect: true}).
                    change(onStateFilterChange);
            
                $('#hp-activity-filter-default').bind('click', function (ev) {
                    presenter.setDefaultFilters();
                });
            
                $(DATE_FILTER).hpSelect();
            
                initTable();
                
                $('#tour-activity-clear').click(function () {
                    presenter.clearSelectedItems();
                });
                $('#tour-activity-delete').click(function () {
                    presenter.deleteSelectedItems();
                });
                
                presenter.init();
                
                this.resume();
            };
        }

        return ActivityResourceView;
    }());
    
    return ActivityResourceView;
});
