//                                    OM
/******************************************************************************
 * @file jquery.hpsumInstallResults.js
 *
 *
 * @section LICENSE
 *
 * HPE Confidential
 * Copyright 2020 Hewlett-Packard Enterprise Company, L.P.
 *
 * @section DESCRIPTION
 *
 * This is a plugin for the showing the install results in a table and also
 * showing the installation logs in a new dialog.
 *
 *
 *******************************************************************************/
define(['hp/model/Session',
        'hpsum/presenter/node/NodePresenter',
        'hpsum/presenter/ilofederation/iloFederationPresenter',
        'hp/core/Localizer',
        'hp/services/Log',
        'hp/services/REST',
        'hp/view/DialogView',
        'text!hpsumpages/node/component_dialog.html',
        'jquery',
        'hp/lib/jquery.hpStatus',
        'lib/jquery.dataTables',
        'hp/lib/jquery.hpToggle'],
function(session, presenter, ilofedpresenter, localizer, log, rest, dialogview, dialoghtml) {
    "use strict";
    //Lets create the plugin.
    (function($) {

        //Adding the plugin as jquery extension.
        $.fn.hpsumInstallResults = function(options) {
            //Write the plugin here

            function InstallResultsTablePlugin(element, params) {
                var container = element;
				var componentsList = [];

                /*!
                 This function will initialize the table.
                */
                this.init = function() {
                    this.nodeid = params;
                    this.rtype = "node";
                    this.viewHandler = {
                        success: function(logdata) {
                            showInstallLog(logdata);
                        },
                        error: function(errorInfo) {
                            showError(errorInfo);
                        }
                    };
                    createTable.call(this);
                };

                /*!
                 This function will set the node id for which the install results need to be set
                 @param nodeid The server node id
                 */
                this.setNodeId = function(nodeid) {
                    this.nodeId = nodeid;
					componentsList = [];
                };

				/*!
                 This function clears the text entered in search text control
                 */
				this.clearSearch = function() 
                { 
                     this.tableInst.fnFilter( '' ); 
                };

                /*!
                 To set a new user handler for showing the logs. If the handler is not
                 set then the logs will shown using dialogview 
                 @param Array handler
                */
                this.viewLogHandler = function(handler)
                {
					if(handler) {
						this.viewHandler = handler[0];
					}
                }

                this.setType = function(type)
                {
                    this.rtype = type[0];
                }

                /*!
                 This function will create the data table fro showing the install results
                 */
                function createTable() {

                    this.tableid = $(container).attr('id') + '-table';
                    var thisinst = this;
                    var tableId = $("#" + this.tableid);

                    $(container).html('<table class="hp-selectable" id="' + this.tableid + '"style="width:100%">' +
                        '<thead>' +
                        '<tr>' +
                        '<th></th>' +
                        '<th>' + localizer.getString("hpsum.oneTouchUpdate.component") + '</th>' +
						'<th>' + localizer.getString("hpsum.oneTouchUpdate.packageStr") + '</th>' +
                        '<th>' + localizer.getString("hpsum.oneTouchUpdate.deploymentStatus") + '</th>' +
                        '<th>' + localizer.getString("hpsum.oneTouchUpdate.log") + '</th>' +
                        '<th></th>' +
                        '<th></th>' +
                        '</tr>' +
                        '</thead>' +
                        '<tbody>' +
                        '</tbody>' +
                        '</table>');

                    var table = $("#" + this.tableid).dataTable({
                        oLanguage: {
                            sEmptyTable: localizer.getString('hpsum.oneTouchUpdate.noComponentsInstalled'),
                            sSearch: localizer.getString('hpsum.common.search')
                        },
                        bPaginate: false,
                        bProcessing: true,
                        bRetrieve: true,
                        bDestroy: true,
                        bFilter: true,
                        bSort: true,
                        bAutoWidth: false,
                        bInfo: false,
                        //aaData: data,
                        aoColumns: [{
                                mDataProp: 'status',
                                sClass: '<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div></div>'
                            }, {
                                mDataProp: 'component_id'
                            }, {
								  mDataProp: 'name'
							}, {
                                mDataProp: 'installation_result'
                            }, {
                                mDataProp: 'view_log'
                            }, {
                                mDataProp: 'node_uri',
                                "bVisible": false
                            }, {
                                mDataProp: 'op_status',
                                "bVisible": false
                            },{
                                mDataProp: 'installation_return_code',
                                "bVisible": false
                            }
                        ],
                        aaSorting: [
                            [0, "asc"]
                        ],
                        fnCreatedRow: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                            // We will get the component logs and show in dialog.
                            
                            $(nRow).click(function(event) {

                                   //this is tr
                                   $("tr.hp-selected",$(this).parent()).removeClass('hp-selected');
                                   //It will triggered on a td element. So the parent is tr
                                         
                                   $(this).addClass('hp-selected');
								   if(aData.installation_return_code != 6)
								   {
										getLogs(aData, thisinst );
								   }
                                   
                            });

                            
                            $('td', $(nRow)).css('vertical-align', 'middle');
                        }
                    });

                    this.tableInst = table;


                }; //createTable ends


                /*!
                 This function will show the install log in different dialog
                 @param data The getcomponentlogs data from the hpsum_service.
                 */
                function showInstallLog(data) {
                    //show component dialog
                    var dialog = new dialogview();
                    dialog.init({
                        contents: dialoghtml,
                        ok: function(elem) {
                            return true;
                        },
                        cancel: function() {}
                    });

                    $('#component_title').html(localizer.getString("hpsum.oneTouchUpdate.deploymentLog"));
                    if (data.hapi.components.component.length > 0) {
                        $('#hpsum-comp-inst-notes').show();
                        $('#hpsum-comp-fail-dep').hide();
                        $('#hpsum-component-id').html(data.hapi.components.component[0].component_id);
                        $('#hpsum-component-installation-notes').html(data.hapi.components.component[0].component_log);
                    }
                } //showInstallLog


                /*!
                 This function will be called when we are not able to the retrived the log details for 
                 a component using getcomponentlogs
                 @param data The getcomponentlogs http error data.
                */
                function showError(data) {
                    //TBD
                    //Will write  another error handling class for server retrieved errors
                } //showError



                /*!
                 This function will get logs for named installed componentusing getcomponentlogs
                 @param rowInfo The row information from the data table.
                 @param uri The uri to be called to get getcomponentlogs
                */
                function getLogs(rowinfo, plugininst ) {

                    var nodeid = rowinfo.node_uri.split("/");
                    if(plugininst.rtype.match(/node/i)){
                        presenter.getComponentLogs(nodeid[nodeid.length-1], [rowinfo.component_id], plugininst.viewHandler);
                    }
                    else{
                        ilofedpresenter.getComponentLogs(nodeid[nodeid.length-1], [rowinfo.component_id], plugininst.viewHandler);
                    }
                } //getLogs


                this.stopLogTimer = function(handler){
					if(handler) {
						 this.stopLogTimer = handler[0];
					}
                }
                /*!
                This function will get all the installed components status using getupdatelist
                */
                this.populateTable = function() {

                    var datatable = this.tableInst;
                    var uri = "";
                    var presenterInst;
					var param;
                    if(this.rtype.match(/node/i)){
                         uri = "/Session/" + session.getToken() + "/node/" + this.nodeId;
                         presenterInst = presenter; //node presenter
						 param = this.nodeId + '/' + 'isDeployResults';
                    } else {
                         uri = "/Session/" + session.getToken() + "/node/ScalableUpdate/" + this.nodeId;
                         presenterInst = ilofedpresenter; //node presenter
						 param = this.nodeId;
                    }
                    presenterInst.getUpdateList(param, {
                        table_id: '#' + this.tableid,
                        success: function(data) {	                            
                            if (data.hapi.hasOwnProperty("node_state")) {
                              if((data.hapi.node_state.match(/Install$/i) || data.hapi.node_state.match(/InstallFrom/i)) || (data.hapi.node_state.match(/error/i) && data.hapi.logs_available == true)){ 
								$('#hpsum-node-live-log-results-panel').show();
                                if(data.hapi.livelog != ""){
                                    $('#hpsum-component-installation-notes').text(data.hapi.livelog);                                                                   
                                    $('#hpsum-component-installation-notes').scrollTop($('#hpsum-component-installation-notes').prop('scrollHeight'));
                                }else{
                                    $('#hpsum-component-installation-notes').text(localizer.getString("hpsum.node.defaultLiveLogMessage"));
                                }
                              }
                              else if(data.hapi.node_state.match(/installdone/i)){
                                $('#hpsum-node-live-log-results-panel').hide();
                                $('#hpsum-component-installation-notes').text("");
                                tableInstance.stopLogTimer();
                              }
                            }
							if(componentsList.length == 0)
							{
								datatable.fnClearTable();
								if (data.hapi.hasOwnProperty("node_type") && data.hapi.node_type.match(/ilo5/i))
								{
									$(this.table_id + ' tr')[1].cells[0].innerHTML = localizer.getString("hpsum.oneTouchUpdate.iLO5NoComponentsInstalled");
								}	
							}
                            if (datatable && data.hapi.hasOwnProperty("components")) {                                
                                for (var ind = 0; ind < data.hapi.components.component.length; ind++) {
                                    var comp = data.hapi.components.component[ind];
                                    var status;
                                    if (comp.installation_return_code >= 0 && comp.installation_return_code <= 6)
                                        status = '<div class="hp-status"><div class="hp-status-value hp-status-ok"><span class="hp-value">ok</span></div></div>';
                                    else
                                        status = '<div class="hp-status"><div class="hp-status-value hp-status-error"><span class="hp-value">error</span></div></div>';
									var viewLog = '<a class="hp-button" style="vertical-align:top; white-space: nowrap;">' + localizer.getString("hpsum.oneTouchUpdate.viewLog") + '</a>';
									if(comp.installation_return_code == 6)
									{
										viewLog = '<a class="hp-button hp-disabled" style="vertical-align:top; white-space: nowrap;">' + localizer.getString("hpsum.oneTouchUpdate.viewLog") + '</a>';
									}
                                    var item = [{
                                            status: status,
                                            component_id: comp.component_id,
                                            name: comp.name,
                                            installation_result: comp.installation_result,
											installation_return_code: comp.installation_return_code,
                                            node_uri: uri,
                                            view_log: viewLog,
                                            op_status: "started"
                                        }
                                    ];
									if(componentsList.indexOf(comp.component_id) == -1)
									{
										componentsList.push(comp.component_id);
										datatable.fnAddData(item);
									}
                                }
                            }
                        },
                        error: function(data) {}
                    });

                }; //populate Table end

                //Constructor code below
                this.init();
            }


            // Plugin initialization code

            var tableInstance = null;
            if (typeof options === "string") {
                //To call the plugin functions after initialization.
                var args = Array.prototype.slice.call(arguments, 1);

                this.each(function() {
                    tableInstance = $.data(this, '_widgethpsumInstallResults');
                    //Lets try to get the data from the element
                    if (!tableInstance) {
                        log.error("This object has not yet been initialized to use deployResultsTable");
                        return;
                    } else if (!$.isFunction(tableInstance[options]) || options.charAt(0) === '_') {
                        log.error("No function by name " + options + ' exist in deployResultsTable');
                        return;
                    }
                    // call method

                    tableInstance[options].call(tableInstance, args);
                });
            } else {
                //Request for a new initialization
                return this.each(function() {
                    tableInstance = $.data(this, '_widgethpsumInstallResults')
                    if (!tableInstance) {
                        tableInstance = new InstallResultsTablePlugin(this, options);
                        $.data(this, '_widgethpsumInstallResults', tableInstance);
                    }
                });
            }
        };
    }(jQuery));
});