// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type (BaselineView)
 * This is a view class for Baseline
 * Provides functions for showing master pane and its action.
 */
define(['hpsum/model/baseline/BaselineResource',
	'hp/view/MasterPaneView',
	'hpsum/presenter/baseline/BaselinePresenter',
	'hpsum/view/baseline/BaselineShowView',
    'hp/core/Localizer',
	'hp/services/IndexService',
    'jquery',
    'lib/jquery-ui-timepicker-addon',
    'lib/jquery.dateFormat',
    'hp/lib/jquery.hpToggle',
	'hp/lib/jquery.hpStatus',
    'hp/lib/jquery.hpUtilizationMeter',
    'hp/lib/jquery.hpSafeClone',
    'hp/lib/jquery.hpEllipsis'],
function(resource, MasterPaneView, presenter, BaselineShowView, localizer, indexService) {"use strict";

    var BaselineView = ( function() {
		
		var TYPE = 'baseline';
		var PAGE = '#hpsum-baseline-page';
		//var SCHEDULE_DIALOG = '#hpsum-baseline-schedule-information';
		var BASELINE_USING_NODES_TABLE = '#hpsum-baseline-using-nodes-table';
		var BASELINE_USING_INFORMATION = '#hpsum-baseline-using-information';
		
        /**
         * @constructor
         * @type {BaselineView}
         */
        function BaselineView() {
			var masterPaneView = new MasterPaneView();
			var template = null;
			
			function renderer(indexResult) {
				var i, html, uri, location_id;
                var item = template.hpSafeClone();
                item.attr('id', '');
                item.show();
                
                $('.hp-status', item).hpStatus(indexResult.status, indexResult.changing);
                if(indexResult.name.match(/^Additional Package/i))
					$('.hp-master-item-name', item).html(localizer.getString("hpsum.group.additionalPackage"));
				else
					$('.hp-master-item-name', item).html(indexResult.name);
                $('.baseline-item-version', item).html('<label class="hp-label">' + localizer.getString("hpsum.baseline.version") + '<label> ' + indexResult.attributes.version);
               	$('.baseline-item-location', item).html('<label class="hp-label">' + localizer.getString("hpsum.common.locationStr") + ':</label>' + '<div class="hp-ellipsis" style="max-width:110px;">' + indexResult.location + '</div>');
               	$('.hp-ellipsis', item).hpEllipsis();
                $('.baseline-item-size', item).html(indexResult.attributes.size);
		if (indexResult.associated_node_count == 0){
			$('.baseline-usingnode-size', item).html('<label class="hp-label" style="margin-left: -15px;">' + indexResult.associated_node_count + localizer.getString('hpsum.baseline.remove.devices') + '</label>'); 
		}
		else if (indexResult.associated_node_count == 1){
			$('.baseline-usingnode-size', item).html('<label><a id="hpsum-master-pane-baseline-node-click" data-baseline-id="' + indexResult.id + '" data-location-id="' + indexResult.location_id +'" class="company-a">' + localizer.getString('hpsum.baseline.remove.assigned') + ' ' + indexResult.associated_node_count + localizer.getString('hpsum.baseline.remove.device') + '</a></label>'); 
		}
		else {
			$('.baseline-usingnode-size', item).html('<label><a id="hpsum-master-pane-baseline-node-click" data-baseline-id="' + indexResult.id + '" data-location-id="' + indexResult.location_id +'" class="company-a">' + localizer.getString('hpsum.baseline.remove.assigned') + ' ' + indexResult.associated_node_count + localizer.getString('hpsum.baseline.remove.devices') + '</a></label>');
		}

                
                var locations = indexService.getLocations();
                
                //This baseline is just added (as per status value), so start InventoryBaseline on it
                // the inventory should happen for local and UNC. For PFW bundles the
                // automatic inventory need not to happen
                if (indexResult.state === "inventory_needed")
                { 
		   if (indexResult.location_type.match(/local|Unc/i))
                   {
                		presenter.startInventory(indexResult);
                   }
                                      
                }
                
                
                html = '<li data-id="all" class="hp-selected">' + localizer.getString("hpsum.common.all") + '</li>';
                
                for(i = 0; i < locations.length; i += 1)
                {
                	html = html + '<li data-id="' + locations[i].location_uri + '">' + locations[i].location_uri + '</li>';
                }
                
                $('#locations', PAGE).html(html);
                
               //Should not use BASELINE_TO_NODE as it affects the filter functionality
               //Currently resource is created with out any options such as BASELINE_TO_NODE
               //need to resolve this later 
                /*
                if (indexResult.children.BASELINE_TO_NODE) {
                    $('.baseline-item-nodes a', item).attr('href', '#/type/show?' +
                        'f_suri=' + indexResult.uri +
                        '&f_an=BASELINE_TO_DEVICE').text(
                            indexResult.children.BASELINE_TO_NODES.length + ' nodes');
                } else {
                    $('.baseline-item-nodes a', item).replaceWith('0 nodes');
                }
                */
                return item;
            }
			
			function onBaselineCountChange(baselineCount)
			{	
				BaselineShowView.associateAddBaselineOptionsPopup(baselineCount);
				
			}
			
			function baselineInventoryInProgress(invInProgress)
			{
				BaselineShowView.disableOrEnableCreateCustom(invInProgress);		
			}
            /**
             * @public
             */
            this.init = function() {
                presenter.init();
			
				template = $('#hpsum-baseline-item-template').detach();			
				
								
				masterPaneView.init({
                    routePrefix: '/' + TYPE,
                    resource: resource,
                    page: $(PAGE),
				    addLink: presenter.getAddLink(),
                    multiSelect: true,
                    dataTableOptions:  {
                        aoColumns : [
                            {fnRender: function (oObj) {
                                return '<div>' + oObj.aData.status +
                                    (oObj.aData.changing ? ' *' : '') +
                                    '</div>';
                            }, mDataProp: 'location'},
                            {fnRender: function (oObj) {
                                return '<a href="#/' + TYPE + '/show/r' + oObj.aData.uri +
                                    '">' + oObj.aData.name +
                                    '</a>';
                            }, mDataProp: 'name'}//, sWidth: '180px'},
                            //{mDataProp: 'attributes.model', sWidth: '80px'}
                        ],
                        aaSorting: [[ 1, "asc" ]],
                        fnRowCallback : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                            $('td:eq(0) > div', nRow).hpStatus();
                            return nRow;
                        }
                    },
                    gridItemRenderer: renderer
                });
                $('#hpsum-baselines-utilization').hpUtilizationMeter();
                $('#hpsum-baselines-utilization').hpUtilizationMeter(65,0,100);
				
				$('#hpsum-master-pane-baseline-node-click').live('click', function(ev) {
						
						// table inint
						$(BASELINE_USING_NODES_TABLE).dataTable({
				oLanguage : {
				    sEmptyTable: localizer.getString("hpsum.group.noMoreNodesAvailable"),
				    sSearch: localizer.getString('hpsum.common.search')
						},
				bPaginate : false,
				sScrollY: "250px",
				bFilter : true,
				bInfo : false,
				bAutoWidth : false,
				bRetrieve :true,
				//aaData : dummyNodeData,
				aoColumns : [{
					mDataProp : 'nodeurl'
				}, {
					mDataProp : 'type'
				}, {
					mDataProp : 'status'
				}],
				aaSorting : [[1, "asc"]],
				bScrollCollapse : true
				});
						// table init end
						
                                                var bundleId = $(this).data("baseline-id"), locId = $(this).data("location-id");
												//alert (locId + '/' + bundleId);
								presenter.getAssociatedNodes({location_id: locId, baseline_id: bundleId}, {
                        		success : function(data) {
									var tableNodes = [];
									var l_nodelist = data.hapi.nodes.node;
									var noofnodes = l_nodelist.length;
									var canbedeleted;
									if (data.hapi.nodes.actively_using_nodes == 0) {
										canbedeleted = true;
									}
									else {
										canbedeleted = false;
									}
									for (var idx = 0; idx < noofnodes; ++idx) {
									tableNodes.push({
									nodeurl: '<a id="hpsum-baseline-assigned-node-click" href="#/node' + '/show/r' + l_nodelist[idx].node_uri + '/getdata">' + l_nodelist[idx].node_name + '</a>',
									type : l_nodelist[idx].type,
									status : l_nodelist[idx].node_status
								});
								
								}
								$('#hpsum-baseline-using-nodes-table').dataTable().fnClearTable();
								$(BASELINE_USING_INFORMATION).dialog({
								modal : true,
								dialogClass : 'hp-simple-dialog',
								position : "center",
								draggable : false,
								resizable : false,
								width : 700	
							});
							var textMessage;
							if (noofnodes != 0) {
								textMessage = localizer.getString("hpsum.baseline.remove.baseline") + data.hapi.nodes.baseline_location + localizer.getString("hpsum.baseline.remove.currentlyAssign") +noofnodes + localizer.getString("hpsum.baseline.remove.assignNodes");
							}
							$('#hpsum-baseline-asso-title-message').text (textMessage);
							$(BASELINE_USING_INFORMATION).dialog("open");
								//$(BASELINE_USING_NODES_TABLE).dataTable().fnAddData(tableNodes);
								$('#hpsum-baseline-using-nodes-table').dataTable().fnAddData (tableNodes);
							},
							error : function(data) {
								 }
                    			});
                                                ev.preventDefault(); 
                                        });
								$('#hpsum-baseline-asso-ok').live ('click', function(ev){
								$('#hpsum-baseline-using-nodes-table').dataTable().fnClearTable();
								$(BASELINE_USING_INFORMATION).dialog("close");
							});
							$('#hpsum-baseline-assigned-node-click').live('click', function(ev) {
								$(BASELINE_USING_INFORMATION).dialog("close");
								$('#hpsum-baseline-using-nodes-table').dataTable().fnClearTable();
							});
							masterPaneView.on("baselineCountChange", onBaselineCountChange);
							masterPaneView.on("inventoryProgress", baselineInventoryInProgress);
										
            };
			
			

            /**
             * @public
             */
            this.pause = function() {
				masterPaneView.pause();
            };

            /**
             * @public
             */
            this.resume = function() {
				masterPaneView.resume();
            };
        }

        return new BaselineView();
    }());

    return BaselineView;
});
