// (C) Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
/**
 * @type {NodeShowOverviewView}
 * Provides functions to show overview/details pane for a node item
 */

define(['hpsum/presenter/node/NodePresenter',
    'hp/core/UrlFragment',
    'hp/core/Router',
    'text!hpPages/core/no_details.html',
    'hp/view/DetailsShowView',
    'hp/view/DialogView',
    'hp/view/NotificationsView',
    'hp/core/Localizer',
    'text!hpsumpages/node/abort_confirm.html',
    'jquery',
    'hp/lib/jquery.hpGridPanels',
    'hp/lib/jquery.hpEllipsis',
    'lib/jquery.ThreeDots',
    'hp/lib/jquery.hpDropMenu',
    'lib/jquery.columnizer',
    'hp/lib/jquery.hpStatus',
    'lib/jquery.dateFormat',
    'hp/lib/date'],
function(presenter, urlFragment,router, noneHtml,DetailsShowView,DialogView, NotificationsView,localizer, abortConfirmHtml){
	"use strict";
	
	var NodeShowInventoryView = (function() {
		var VIEW = '#hpsum-nodes-inventory';
		var ROOT = '#hpsum-node-show-inventory',
			SPINNER = '#hpsum-node-inventory-spinner',
	  		PANELS = '.hp-grid-panels',
	  		DETAILS ='#hpsum-node-inventory-details',
	  		BASELINE ='#hpsum-node-bundle',
	  		TITLE = '#hpsum-nodes-details-title',
	  		STATUS = '#hpsum-nodes-details-status',
	  		TEXT ='#hpsum-node-inventory-progress-text',
	  		TYPE ='#hpsum-node-type',
	  		CURRENT_STATUS ='#hpsum-node-inventory-current-status',
            DESCRIPTION = '#hpsum-node-description',
            ACTIONS = '.hp-details-actions',
            ABORT_ACTION ='#hpsum-nodes-abort-action',
            SELECTOR = '#hpsum-nodes-panel-selector';
          
       var ABORT_TITLE = '#hpsum-nodes-abort-title',
       	   ABORT_ERROR = '#hpsum-abort-err';
        
        function NodeShowInventoryView(){
        	
        	var noItem;
        	var abortInProgress = false;
        	var detailsShowView = new DetailsShowView();
        	var notificationsView = new NotificationsView();
        	var timer = null;
        	var thisNode;
        	function onSelectionChange(selection) {
        		urlFragment.replaceHrefUris(ROOT, selection.uris);
        	}
        	
        	function onItemChange(item){
        		item = item.hapi;
        		thisNode = item;
        		noItem.remove();
        		var i;
        		if(item.node_state.match(/inventory/i)){
        			notificationsView.clear();
        			$(SPINNER).show();
        			$(TITLE).removeClass('hp-unavailable');
        			$(TITLE).text(item.name);
        			$(TEXT).text(localizer.getString('hpsum.node.scanning') + ' ' + item.type + ' ' + item.name);
        			$(CURRENT_STATUS).text(item.node_status);
        			$('.hp-grid-panels').css({"display":""});
        			$('.hp-grid-panels').hpGridPanels('reset');
        			$(STATUS).hpStatus(item.status, item.changing).
                        removeClass('hp-unavailable');
                    showInventoryProgress(item);
                    var tablecontents = "";
    				tablecontents = "<table>";
                    for (var key in item) {
  						if (item.hasOwnProperty(key)) {
  							if(key.match(/node/i))
  								continue;
  							tablecontents += "<tr>";
      						tablecontents += "<td>" + key + "</td>";
      						tablecontents += "<td>" + item[key] + "</td>";
      						tablecontents += "</tr>";
  							}
					}
					tablecontents += "</table>";
					$(DETAILS).html(tablecontents);
        		}
        		else
        			router.go(urlFragment.replaceView(router.location(), 'show'));
        	}
        	
        	function showInventoryProgress(item){
        		    timer = setInterval(function () {
            		
            		presenter.getNodeStatus(item, {
                				success : function(data) {
                    				onNodeStatusSuccess(data);
                    		 	},
                    			error : function(errorInfo) {
                        			onNodeStatusError(errorInfo);
                    			}
                			});
                			
                }, 3000);
        	}
        	
        	function onNodeStatusSuccess(data){
        		if(thisNode.node_id == data.hapi.node_status.node_id) {
        			$(CURRENT_STATUS).text(data.hapi.node_status.node_status);
        			if(data.hapi.node_status.node_state.match(/uan|inventoryerror|idle/i)){
        				clearInterval(timer);
        				presenter.refreshIndexResults();
        			}
        		}
        	}
        	
        	function onNodeStatusError(error){
        		
        	}
        	
        	function onItemError(error){
        		$(ROOT).append(noItem);
        	}
        
        	
        	function onAbort(ev){
        		if (! abortInProgress) {
                   abortInProgress = true;
                    
                   var contents = $(abortConfirmHtml);
                   localizer.localizeDom(contents);
                    $(ABORT_TITLE, contents).text(localizer.getString('hpsum.node.abortFor', [presenter.selectionLabel()]));
                    var dialogView = new DialogView();
                    dialogView.init({contents: contents,
                        ok: function () {
                                presenter.abortAction({
                                    success : function(){
                                    	abortInProgress = false;
                                    	notificationsView.add({summary: localizer.getString('hpsum.node.abortInProgress')}, true);
                                    },
                                    error : function(msg){
                                    	abortInProgress = false;
                                    	notificationsView.add({summary: msg}, true);
                                    }
                                });
                        },
                        cancel: function () {
                            abortInProgress = false;
                        }
                    });
                }
                
                ev.preventDefault();
        	}
        	
        	/* 
        	 *  Public Functions
        	 */
        	
        	this.init = function() {
        		noItem = $(noneHtml);
        		detailsShowView.init($(SELECTOR));
        		notificationsView.init({context: $(VIEW),
                    allLocation: '#/node/show/activity',
                    resource: presenter.resource()});
        		$(PANELS).hpGridPanels();
        		$(ACTIONS).hpDropMenu();
                $('#hpsum-activity-actions').hide();
        		$(DESCRIPTION).ThreeDots({max_rows: 3, alt_text_t:true});
        		this.resume();
        		$(ABORT_ACTION).bind('click', onAbort);
        	};
        	
        	this.resume = function() {
        		$(PANELS).hpGridPanels('reset');
        		presenter.on("selectionChange", onSelectionChange);
                presenter.on("itemError", onItemError);
                presenter.on("itemChange", onItemChange);
                if (notificationsView.resume) {
                    notificationsView.resume();
                }
               
        	};
        	
        	this.pause = function() {
				presenter.off("selectionChange", onSelectionChange);
                presenter.off("itemChange", onItemChange);
                presenter.off("itemError", onItemError);
                if (notificationsView.pause) {
                    notificationsView.pause();
                }
        	};
      	
        	
        }
		
		return new NodeShowInventoryView();
	}());
	
	return NodeShowInventoryView;
});
