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

define(['hpsum/presenter/ilofederation/iloFederationPresenter',
    'hp/core/Router',
    'hp/core/UrlFragment',
    'hp/core/Notifications',
    'hp/view/FormStateView',
    'hp/model/Session',
    'hp/core/Localizer',
    'hp/view/DialogView',
    'text!hpPages/core/header_help.html',
    'jquery',
    'hp/lib/jquery.hpStackedPanels',
    'hp/lib/jquery.hpSearchCombo',
    'hp/lib/jquery.hpCollapsible',
    'hp/lib/jquery.hpToggle',
    'lib/jquery.dataTables',
    'hpsum/common/jquery.hpsumBrowse',
    'hp/lib/jquery.hpSelect'],
function(presenter,router, urlFragment, notifications, FormStateView, session, localizer,DialogView,headerHelpHtml) { "use strict";

    var iloOfflineDeployView = (function() {
      
        var OK = '#hpsum-node-offdeploy-ok';
        var CANCEL ='#hpsum-node-offdeploy-close';
        var FORM = '#hpsum-node-offdeploy-form';
        var TITLE = '#hpsum-node-details-title';
        var TYPE ='#hpsum-node-type';
        var NAME = '#hpsum-node-name',
            INTERFACEILO = '#hpsum-node-interface',
            OFFLINEDEPLOYOPTION= '#hpsum-ilofederation-offdeploy-option',
            FILTERINGDIV='#hpsum-iofed-offdep-filtering',
            FILTERCOLLAPSE= '#hpsum-ilofed-offlinedeploy-collapsible',
            BROWSE_LOCATION_ERROR = '#hpsum-invalid-location-error',
            INSTALLED_SYSTEM_TYPE_TABLE = '#ilofed-installed-system-type-table',
            OFFLINE_DEPLOY_CONFORMATION = '#hpsum-offline-deploy-confirm',
            SERVER_RESET_COUNT='#hpsum-offline-deploy-server-count',
            FILTER_NOT_SELECTED = '#hpsum-filter-error',
            ISO_PATH_ERROR = '#hpsum-node-isolocation-error-block',
            SELECTALL = '#ilofed-offline-deploy-selectall',
            DESELECTALL = '#ilofed-offline-deploy-deselectall',
            FORM = '#hpsum-node-offdeploy-form',
            URL_ICON = '#hpsum-url-icon',
			SPLASH_DIALOG = '#hpsum-validate-wait-dialog',
			SPLASH_SPINNER = '#hpsum-add-spinner',
			URL_EMPTY = '#hpsum-node-isolocation-empty-error',
			SCALABLE_OFFLINE_DEPLOY_BROWSE_PANEL = "#hpsum-ilofed-offlinedeploy-browse-panel";

        var poweredOnServerCount;
        
        
        /**
         * Constructor
         */
        function iloOfflineDeployView() {
          
            var formStateView = new FormStateView();
            var inventoryInProgress = false;
            var sugItem=null;
            var searchResults = [];
            var selectedServers =0;
            var instiloFedOfflineBrowse;
            var offlineDeployConfirmationDialog;
			var validateWaitDialog;
                
            function onItemChange(item) {
            	item = item.hapi;
				if(item.sug_state.match(/inventory/i)) {
					$(CANCEL).trigger('click');
				}
                if (item) {
                    $(TITLE).text(item.sug_name);
                    $(NAME).text(item.sug_name);
                    $(INTERFACEILO).text(item.sug_interface_ilo_ip);
                 
                    sugItem= item;
                    $(FILTERCOLLAPSE).hpCollapsible('expand');
                    $("#ilofed-installed-system-type-table > tbody > tr").remove();
                    $("#ilofed-installed-system-type-table_filter").remove();
                    $("#ilofed-installed-system-type-table_processing").remove();
                       // Populate the all the discovered server models and counts
                    if (item.server_types && item.server_types.length > 0) {
                            
                        var systemsTable = initSystemsTable();
                        systemsTable.fnClearTable();

                            // Go ahead and populate all the systems in the systems table
                        var idx;
                        for (idx = 0; idx < item.server_types.length; idx++) {
                            var system = item.server_types[idx];
                            var selectedtoggle = '<input id="selectToggle-' + idx + '" class="toggle" type="checkbox" checked/>';
                            systemsTable.fnAddData([{selected:selectedtoggle, server_model : system.server_model, count : system.count}]);
                        }
                        
                        $(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr').addClass('hp-selected');
                        $('.toggle').hpToggle({
                            unchecked : localizer.getString("hpsum.oneTouchUpdate.select"),
                            checked : localizer.getString("hpsum.oneTouchUpdate.selected")
                        });
                      $(INSTALLED_SYSTEM_TYPE_TABLE + " tbody tr").click(function(e) {
                        var srcElem;
                                    //Check if firefox or (chrome and IE)
                        if (e.srcElement) {
                            srcElem = e.srcElement;
                                            //Chrome and IE
                            } else {
                            srcElem = e.target;
                                        //Firefox
                            }
                            var data = systemsTable.fnGetData(this);
                            var clickedCellIndex = srcElem.cellIndex;
                            var selectid = data.selected.split('"');
                            selectid ='#'+selectid[1];
                            if(clickedCellIndex === undefined){
                                if(srcElem.className =='hp-on'){
                                    $(this).removeClass('hp-selected');
                                    formStateView.setMessage({
                                        summary : localizer.getString('hpsum.ilofederation.deselectedModel',
                                                        [data.server_model]),
                                        status : "info"
                                    });
                                    $(selectid).removeAttr('checked');
                                }else{
                                     $(FILTER_NOT_SELECTED).hide();
                                     $(this).addClass('hp-selected');
                                     formStateView.setMessage({
                                            summary : localizer.getString('hpsum.ilofederation.selectedModel',
                                                        [data.server_model]),
                                            status : "info"
                                        });
                                    $(selectid).attr('checked', 'checked');
                                }
                                $(selectid).trigger('change');

                            }
                            else {
                                if ($(this).hasClass('hp-selected')) {
                                        $(selectid).removeAttr('checked');
                                        formStateView.setMessage({
                                            summary : localizer.getString('hpsum.ilofederation.deselectedModel',
                                                        [data.server_model]),
                                            status : "info"
                                    });
                                    }
                                    else {
                                        $(selectid).prop('checked', true);
                                        formStateView.setMessage({
                                        summary : localizer.getString('hpsum.ilofederation.selectedModel',
                                                        [data.server_model]),
                                        status : "info"
                                    });
                                    }
                                    $(selectid).trigger('change');
                                    $(this).toggleClass('hp-selected');

                            }

                        });
                    }

                    // set the number of servers to be reset during offline deployment process
                    poweredOnServerCount = item.powered_on_servers;
                }
                

            }


            function initSystemsTable() {
                
                if($.fn.DataTable.fnIsDataTable( $(INSTALLED_SYSTEM_TYPE_TABLE)[0] ))
                {
                    $(INSTALLED_SYSTEM_TYPE_TABLE).dataTable().fnDestroy(); 
                }  
                                
                return $(INSTALLED_SYSTEM_TYPE_TABLE).dataTable({
                    bPaginate : false,
                    bLengthChange : false,
                    bFilter : false,
                    bSort : false,
                    bInfo : false,
                    bAutoWidth : false,
                    bRetrieve : true,
                    aoColumns : [
                        {mDataProp: 'selected',"sWidth":"30%"},                       
                        {mDataProp: 'server_model', "sWidth":"30%"},
                        {mDataProp: 'count', "sWidth":"30%"}
                        ]
                });
            }
            function onPathEdit() {
                $(BROWSE_LOCATION_ERROR).hide();
                $(ISO_PATH_ERROR).hide();
                instiloFedOfflineBrowse.removeInputClass("hp-error");
                $(URL_EMPTY).hide();
				$(URL_ICON).removeClass('hpsum-error');
                instiloFedOfflineBrowse.setInputEvent('offkeyup', onPathEdit);
            }


             function onHandleInvalidPath(hapi) {
               if (hapi.hcode == 5) {
                    $(BROWSE_LOCATION_ERROR).text(localizer.getString('hpsum.baseline.add.inValidLocation'));
                    instiloFedOfflineBrowse.addInputClass("hp-error");
                    $(BROWSE_LOCATION_ERROR).show();
                    instiloFedOfflineBrowse.setInputEvent('onkeyup', onPathEdit);
                    instiloFedOfflineBrowse.triggerDialogEvent('clickcancel');
                        $(ADD).attr("disabled", true);
                } else {
                    $(BROWSE_LOCATION_ERROR).hide();
                    instiloFedOfflineBrowse.removeInputClass("hp-error");
                    instiloFedOfflineBrowse.setInputEvent("offkeyup", onPathEdit);
                }
            }
						
			function showValidateWait(msg) {					
					
					if (!validateWaitDialog) {
						validateWaitDialog = $(SPLASH_DIALOG);
						validateWaitDialog.dialog({
							modal : true,
							dialogClass : 'hp-simple-dialog',
							position : "center",
							draggable : false,
							resizable : false,
							width : 260,
							height : 180
						});
					}
					if(msg == undefined)
						msg = localizer.getString('hpsum.ilofederation.validateInProgress');
					$('#hpsum-validate-wait-message', validateWaitDialog).html(msg);
					$(SPLASH_SPINNER).show();
					msg='';
					validateWaitDialog.dialog('open');
				}
				
			function closeValidateWait() {
					$(SPLASH_SPINNER).hide();
					if (validateWaitDialog) {
						validateWaitDialog.dialog('close');
					}
			}

            function onValidate(startdeploy){
			
			    if(startdeploy == null)
					startdeploy = false;
					
                var isValidIp = false;
                var urlEntered = instiloFedOfflineBrowse.getLocation().toLowerCase(); 
				if (urlEntered.length == 0)
				{
				    //put in the proper error  message here
					$(URL_EMPTY).fadeIn('fast');
                   formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.requiredFieldMissing',
                                                        [localizer.getString('hpsum.ilofederation.isoimage')]),
                            status : "error"
                    });
					instiloFedOfflineBrowse.addInputClass('hp-error');
					instiloFedOfflineBrowse.setInputEvent('onkeyup', onPathEdit);
					$(URL_ICON).removeClass('hpsum-ok').addClass('hpsum-error');
					return false;
				}

                var parser = document.createElement('a');
                parser.href = urlEntered;
                var ip = parser.hostname;

				//localhost will not be reachable by iLO
                if(ip.toLowerCase() == 'localhost')
                   isValidIp = false;
                    //ipv4 match
                if(ip == '0.0.0.0' | ip == '255.255.255.255'){
                    onItemAddError(localizer.getString('hpsum.node.ipCannotBe') + ' ' + ip);
                    isValidIp = false;
                }
                var patt = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
                if(ip.match(patt))
                    isValidIp = true;
                else{
                    patt = /^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))?$/;
                    if(ip.match(patt))
                        isValidIp = true;
                    else
                    {
                        patt = /^[a-zA-Z0-9-_]+(\.[a-zA-Z0-9-_]+)*\.([a-zA-Z]{2,4})$/;
                        //FQDN match
                        if(ip.match(patt))
                            isValidIp = true;                           
                        else{
                            //check for unqualified domain name or netbios hostname
                            var hostnamepatt = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$";
                            if(ip.match(hostnamepatt))
                                isValidIp = true;                            
                        }
                     }
                }

                var protocolUsed = parser.protocol; 
                if( !(protocolUsed != "https:" || protocolUsed != "http:") || (!isValidIp))
                {
                    instiloFedOfflineBrowse.addInputClass('hp-error');
                    instiloFedOfflineBrowse.setInputEvent('onkeyup', onPathEdit);
                    $(ISO_PATH_ERROR).fadeIn('fast');
                     formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.validISOrequired'),
                            status : "error"
                        });
                    $(URL_ICON).removeClass('hpsum-ok').addClass('hpsum-error');
                    return false;

                }
                 else
                 {
                    //var isoPattern  = /\.(iso)+$/;
					var isoPattern  = /\/*\.(iso)+$/;
                    if(!urlEntered.match(isoPattern))
                    {
                        instiloFedOfflineBrowse.addInputClass('hp-error');
                        instiloFedOfflineBrowse.setInputEvent('onkeyup', onPathEdit);
                        $(ISO_PATH_ERROR).fadeIn('fast');
                        formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.validISOrequired'),
                            status : "error"
                        });
                        $(URL_ICON).removeClass('hpsum-ok').addClass('hpsum-error');
                        return false;
                    }                   
                    
                 }
				 
				showValidateWait();
				var data;
                var retcode;
				
				presenter.validate({ url_path: instiloFedOfflineBrowse.getLocation() 
										},
										{
											success:function(data){
                                                retcode = data.hapi.hcode;
												closeValidateWait();
                                                 if(retcode == 0)
                                                 {
													instiloFedOfflineBrowse.removeInputClass('hp-error');
                                                    $(URL_ICON).removeClass('hpsum-error').addClass('hpsum-ok');
                                                    $(ISO_PATH_ERROR).fadeOut('fast');
													if(startdeploy)
														onValidateSuccess();
														
                                                    return true;

                                                 }
                                                 else
                                                 {
                                                    instiloFedOfflineBrowse.addInputClass('hp-error');
                                                    instiloFedOfflineBrowse.setInputEvent('onkeyup', onPathEdit);
                                                    $(ISO_PATH_ERROR).fadeIn('fast');
                                                    formStateView.setMessage({
                                                        summary : localizer.getString('hpsum.ilofederation.validISOrequired'),
                                                        status : "error"
                                                    });
                                                    $(URL_ICON).removeClass('hpsum-ok').addClass('hpsum-error');
                                                    return false;
                                                 }
											},
											error:function(data){
												closeValidateWait();
                                                instiloFedOfflineBrowse.addInputClass('hp-error');
                                                instiloFedOfflineBrowse.setInputEvent('onkeyup', onPathEdit);
                                                $(ISO_PATH_ERROR).fadeIn('fast');
                                                formStateView.setMessage({
                                                     summary : localizer.getString('hpsum.ilofederation.validISOrequired'),
                                                     status : "error"
                                                });
                                                $(URL_ICON).removeClass('hpsum-ok').addClass('hpsum-error');
                                                return false;
											}
										});
             }

            function deployOptionChanged(val){
                if($(OFFLINEDEPLOYOPTION).val() == 'hpsum' || val =='hpsum'){
                    instiloFedOfflineBrowse.setBrowseButtonText(localizer.getString("hpsum.common.browse"));
                    instiloFedOfflineBrowse.setBrowseButtonEvent('default', null);
                }else{
                    instiloFedOfflineBrowse.setBrowseButtonText(localizer.getString("hpsum.baseline.show.validate"));
                    instiloFedOfflineBrowse.setBrowseButtonEvent('onclick', onValidateClick);
                }

            }
            
            function onValidateClick() {
            	onValidate(false);
            }
            
            function getAllSelectedServerTypes()
            {

                var selectedList = [];
                selectedServers =0;
                var totalRows = $(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr').size();
                var selectedRows = $(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr.hp-selected').size();

                // If all the rows stay selected, we do not have to filter by servers
                if (totalRows != selectedRows) {
                    $(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr.hp-selected').each(function(index, value){
                        var list = $('td',value);
                        selectedServers +=  Number($(list[2]).text());
                        selectedList.push($(list[1]).text());
                    });
                } else {
                    selectedList.push("AllSelected");
                }

                return selectedList;
            }

            function onDeploy(ev)
            {
              
				 var mode;
                if($(OFFLINEDEPLOYOPTION).val() != 'hpsum'){
                    mode = 1;
                }else{
                    mode = 0;
                }

                var serverTypes = getAllSelectedServerTypes();

                if( serverTypes.length != 0 ) {
                    if (serverTypes[0] == "AllSelected")
                        serverTypes = [];
                }
                    
                presenter.deploy(  {  deploy_mode:mode,
                                      url_or_path: instiloFedOfflineBrowse.getLocation(), 
                                      server_type_filter: serverTypes,
                                      sug_id : sugItem.sug_id
                                 },
                                 {
                                    success:function(data){

                                    },
                                    error:function(data){

                                    }
                                });
                $('#hpsum-node-offdeploy-close').trigger('click');
				
				ev.preventDefault();
               
            }
			
			function onValidateSuccess()
			{	
				var serverTypes = getAllSelectedServerTypes();

                    if( serverTypes.length == 0 )
                    {
                        $(FILTER_NOT_SELECTED).fadeIn(400, function(){});
                        formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.filternotSelectedError'),
                            status : "error"
                        });
                        ev.preventDefault();
                        return false;
                    }
                    else 
                    {
                        $(FILTER_NOT_SELECTED).fadeOut(400, function(){});
                    }
		                        var serverCount =0;
                    if (serverTypes[0] == "AllSelected") 
                        serverCount = poweredOnServerCount;
                    else
                        serverCount = selectedServers;

                    

                    $(SERVER_RESET_COUNT, offlineDeployConfirmationDialog).text(serverCount);

                   
                    new DialogView({contents: offlineDeployConfirmationDialog,
	                    position : "center",
	                    ok: function (elem) {	                        
	                       onDeploy();
	                    },
	                    cancel: function () {
	                        
	                    }
	                });
			}

			function onInvalidPackageSelection(){
            	showInfoDialog();	
            }
            
            this.resume = function () {
            	presenter.on('itemChange', onItemChange);
                $(FILTER_NOT_SELECTED).hide();
				$(URL_EMPTY).hide();
		 selectedServers =0;		
                deployOptionChanged();

            };
            
            this.pause = function () {
            	presenter.off('itemChange', onItemChange);
                $(ISO_PATH_ERROR).fadeOut('fast');
				$(URL_EMPTY).fadeOut('fast');
                instiloFedOfflineBrowse.removeInputClass('hp-error');
                formStateView.reset();
            };

            /**
             * @public
             */
            this.init = function () {
              
				var resource = router.location().split('/');
                	resource = resource[1];
                	if(resource === 'node')
                		$(TYPE).val("Unknown");
                	else
                		$(TYPE).val(resource);
                
                var options = 	{
									command : 'init',
									panelLabel: "hpsum.ilofederation.isoimage",
									panelLabelStyle: "",
						            panelHelp: "",
						            panelBrowseText: "hpsum.baseline.show.validate",
						            bshowXml: false,
						            onHandleInvalidPath: onHandleInvalidPath,
						            onInvalidPackageSelection: onInvalidPackageSelection
						        };
				$(SCALABLE_OFFLINE_DEPLOY_BROWSE_PANEL).hpsumBrowse(options);
				
				instiloFedOfflineBrowse = $(SCALABLE_OFFLINE_DEPLOY_BROWSE_PANEL).data('plugin_hpsumBrowse');
				
               	$('#hpsum-node-offdeploy-close').click(function () {
                    formStateView.reset();
                    router.go(urlFragment.replaceView(router.location(), 'show'));
                });

                $(FILTER_NOT_SELECTED).hide();

                offlineDeployConfirmationDialog = $(OFFLINE_DEPLOY_CONFORMATION).detach().show();
               
               var ROUTE_PREFIX = '/'+ resource +'/offlinedeploy';


                formStateView.init({
                        form : FORM,
                        routePattern : ROUTE_PREFIX + '.*',
                        autoTrack : true
                });
               
               $(OFFLINEDEPLOYOPTION).hpSelect().on('change', deployOptionChanged);
                
                $(OK).on('click', function(ev) {
                    onValidate(true);                    
                    ev.preventDefault();
                });
                
                $(SELECTALL).on('click', function(ev){
			    	$(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr').each( function () {
		                $(this).addClass('hp-selected');
		                var temptable = $(INSTALLED_SYSTEM_TYPE_TABLE).dataTable();
		                var data = temptable.fnGetData(this);
                        var selectid = data.selected.split('"');
                        selectid ='#'+selectid[1];
                         formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.allselected'),
                            status : "info"
                        });
                        $(selectid).attr('checked', 'checked');
                        $(selectid).trigger('change');
		            });
			    });
				
				$(DESELECTALL).on('click', function(ev){
			    	$(INSTALLED_SYSTEM_TYPE_TABLE + ' tbody tr').each( function () {
		            	$(this).removeClass('hp-selected');
		            	var temptable = $(INSTALLED_SYSTEM_TYPE_TABLE).dataTable();
		            	var data = temptable.fnGetData(this);
                        var selectid = data.selected.split('"');
                        formStateView.setMessage({
                            summary : localizer.getString('hpsum.ilofederation.alldeselected'),
                            status : "info"
                        });
                        selectid ='#'+selectid[1];
                        $(selectid).removeAttr('checked');
                        $(selectid).trigger('change');
		            });
			    });
				
                $(FILTERCOLLAPSE).hpCollapsible();

                 if ($('.hp-details-header-controls', $(FORM).parent()).length === 0) {
                    var headerHelp = $(headerHelpHtml);
                    localizer.localizeDom(headerHelp);
                    $('.hp-details-header', $(FORM).parent()).append(headerHelp);
                }
                $(ISO_PATH_ERROR).fadeOut('fast');

                
                this.resume();
            };
        }

        return new iloOfflineDeployView();
    }());
    
    return iloOfflineDeployView;
});
