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

define(['hpsum/model/task/TaskResource',
    'hpsum/presenter/tasks/TasksPresenter',
    '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',
    'hp/lib/jquery.hpProgressBar',
    'hp/lib/jquery.hpCollapsible'],

function(resource, Presenter, linkTargetBuilder, localizer) { "use strict";

    var TasksView = (function() {
      
        var PAGE = '#tour-tasks-page';
        var FILTERBAR_CONTROL = PAGE + ' .hp-filterbar-control';
        var FILTER = '#hp-tasks-filter';
        var DATE_FILTER = '#hp-tasks-date-filter';
        var DATE_MENU = '#hp-tasks-date-menu';
        var TABLE = '#tour-tasks';
        var TABLE_WRAPPER = '#tour-tasks_wrapper';
        var DETAILS_TEMPLATE = '#tour-tasks-details-template';
        var BODY = '#hp-body-div';
        var FILTERBAR_OPEN = 'hp-filterbar-open';
        
        var USERS = ['no one', 'Sam', 'Wilma', 'Fred'];
      
        /**
         * Constructor
         */
        function TasksView() {
          
            var presenter = new Presenter();
            var dataTable;
            var detailsTemplate;
            
            function closeFilterbar() {          
                $(PAGE).removeClass(FILTERBAR_OPEN);
            }

            function openFilterbar() {
                $(PAGE).addClass(FILTERBAR_OPEN);
            }
            
            function toggleFilterbar() {
                if (! $(PAGE).hasClass(FILTERBAR_OPEN)) {
                    openFilterbar();
                } else {
                    closeFilterbar();
                }
            }
            
            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');
                        }
                    });
                }
            }
            
            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) {
                    
                } else {
                    presenter.setSelectedUris([uri]);
                }
            }
            
            function onIndexResultsChange(indexResults) {
                $('.hp-tasks-title').html(indexResults.count + ' Tasks');
                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-task-state-change').click(function (ev) {
                    var indexResult = dataTable.fnGetData($(this).parents('tr')[0]);
                    stateChange(indexResult);
                    ev.stopPropagation();
                });
            }
            function toggleExpansion(TaskRow) {
                if (TaskRow.hasClass('hp-expanded')) {
                    collapseTask(TaskRow);
                } else {
                    expandTask(TaskRow);
                }
            }
            function expandTask(TaskRow) {
                if (! $('.hp-collapser', TaskRow).hasClass('hp-active')) {
                    $('.hp-collapser', TaskRow).addClass('hp-active');
                    TaskRow.addClass('hp-expanded');
                    var details = generateDetails(TaskRow);
                    dataTable.fnOpen(TaskRow[0], details[0], 'hp-row-details-cell' );
                    details.slideDown(400);
                }
            }
              function generateDetails(TaskRow) {
                var indexResult = dataTable.fnGetData(TaskRow[0]);
                var details = detailsTemplate.clone();
                
                $.each(indexResult.earlierLogMessages, function (index, tasksNote) {
                    appendNote(details, tasksNote);
                });
                
                $('.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 collapseTask(TaskRow) {
                if ($('.hp-collapser', TaskRow).hasClass('hp-active')) {
                    $('.hp-collapser', TaskRow).removeClass('hp-active');
                    $('.hp-row-details', TaskRow.next()).slideUp(400, function () {
                        TaskRow.removeClass('hp-expanded');
                        dataTable.fnClose(TaskRow[0]);
                    });
                }
            }
            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').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 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-tasks-filter-default').bind('click', function (ev) {
                    presenter.setDefaultFilterProperties();
                });
                
                $(DATE_FILTER).hpSelect().change(onDateFilterChange);
                $('#hp-tasks-date-range-from').datepicker();
                $('#hp-tasks-date-range-to').datepicker();
                
                $(FILTERBAR_CONTROL).bind('click', toggleFilterbar);
            }
            
            function initActions() {
                $('#tour-tasks-actions').hpDropMenu();
                
                $('.hp-header-select-all').click(selectAll);
                
                $('#tour-tasks-dismiss').click(function () {
                    presenter.dismissSelected();
                });
                
                $('#tour-tasks-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, sClass: "hp-icon"},
                        // status
                        {fnRender: function (oObj) {
                            return '<div class="hp-status">' + oObj.aData.status +
                                (oObj.aData.changing ? ' *' : '') +
                              '</div>';},
                          sWidth: 20, sClass: "hp-icon"},
			// source
                        {fnRender: function (oObj) {
                            return linkTargetBuilder.makeLink(oObj.aData.sourceName,
                                oObj.aData.sourceUri);}
                        },
                        // progress
                        {fnRender: function (oObj) {
                            return '<span class="hp-progress hp-condensed"></span>' +
                              '' + oObj.aData.progress + '%';},
                          sWidth: 100},
                        // action
                        {mDataProp: "name"},
                        // progress step
                        {mDataProp: "progressStep"},                        
                        // 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%'}
						
                    ],
                    aaSorting: [[ 4, "desc" ]],
                    fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                        $('td:eq(1) > div.hp-status', nRow).hpStatus();
                        $('td:eq(2) span', nRow).hpProgressBar(aData.progress);
                        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 = 'Tasks';
                $('#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 TasksView();
    }());
    
    return TasksView;
});
