define(['hp/core/EventDispatcher',
                                'hp/core/Localizer',
                                'jquery',
                                'hp/lib/jquery.hpStatus',
                                'lib/jquery.dataTables',
                                'hp/lib/jquery.hpCollapsible',
                                'hp/lib/jquery.hpToggle'],
function (EventDispatcher, Localizer) {
    "use strict";
    (function ($) {
        // Create the defaults once
        var pluginName = "hpsumInstallSetComponents",
defaults = {
    nodeItem: null
};
        var l_data = null;
        var l_el = null;
        var l_nodeItem = null;        
        var sortDirection = 'desc', sortColumn = 0;
        var INSTALLSET_COMPONENT_HEADER = "#installset-component-details-header";
        // The actual plugin constructor
        function Plugin(element, options) {
            this.element = element;

            // jQuery has an extend method which merges the contents of two or
            // more objects, storing the result in the first object. The first object
            // is generally empty as we don't want to alter the default options for
            // future instances of the plugin
            this.options = $.extend({}, defaults, options);
            this._defaults = defaults;
            this._name = pluginName;

            this.init();
        }

        Plugin.prototype = 
		{
		    init: function () {
		        $(this.element).addClass('hpsumInstallSetComponents');
		        if (this.options.command == 'init')
		        {
		            this.initialize(this.element, this.options);
		        }		        							
		    },

		    initialize: function (el, options) {
		        var plugin = this;
		        plugin.populateComponentsTable(el, options.data);
		    },

		    reinitialize: function () {
		        if (this.options.nodeItem == undefined) {
		            window.console.error("reinitialize before init is not allowed");
		            return;
		        }
		        this.initialize(this.element, this.options);
		    },
		   
		    initiInstallSetComponentTable: function (tableid) {
		        var oTab = $(tableid).dataTable({
		            oLanguage: {
		                sEmptyTable: Localizer.getString('hpsum.common.installSetNoCompFound'),
		                sSearch: Localizer.getString('hpsum.common.search')
		            },
		            bPaginate: false,
		            bProcessing: false,
		            bFilter: true,
		            bSort: true,
		            bAutoWidth: false,
		            bInfo: false,
		            bRetrieve: true,
		            bDestroy: true,
		            aoColumns:
                    [
                         {
                             mDataProp: 'order', fnRender: function (oObj) {
                                 return oObj.aData.order;
                             }
                         },
                          {
                              mDataProp: 'action', fnRender: function (oObj) {
                                  return oObj.aData.action;
                              }
                          },
                          {
                              mDataProp: 'filename', fnRender: function (oObj) {
                                  return oObj.aData.filename;
                              }, sWidth: 180
                          },
                          {
                              mDataProp: 'name', fnRender: function (oObj) {
                                  return oObj.aData.name;
                              }, swidth: '350px'
                          },                        
                          {
                            mDataProp: 'version', "bVisible": false,
							fnRender: function (oObj) {
                                return oObj.aData.version;
                            }, sWidth: 0
                        },
						{
                            mDataProp: 'installed_version', fnRender: function (oObj) {
                                return oObj.aData.installed_version;
                            }
                        },
                        {
                            mDataProp: 'type', fnRender: function (oObj) {
                                return oObj.aData.type;
                            }, sWidth: 120
                        },
                        
                        {
                            mDataProp: 'updatedby', fnRender: function (oObj) {
                                var updatedByString = "";
                                for (var idx = 0; idx < oObj.aData.updatedby.length; idx++) {
                                    if (oObj.aData.updatedby[idx].match(/uefi/i))
                                    {
                                        oObj.aData.updatedby[idx] = "UEFI";
                                    }
                                    updatedByString = updatedByString + oObj.aData.updatedby[idx] + ',';
                                }
                                return updatedByString.slice(0, -1);

                            }
                        },
                        {
                            mDataProp: 'waittime', fnRender: function (oObj) {
                                return oObj.aData.waittime;
                            }, sWidth: 120
                        },
                        {
                            mDataProp: 'activates', fnRender: function (oObj) {
                                return oObj.aData.activates;
                            }
                        }
                    ],
		            fnCreatedRow: function (nRow, aData, iDataIndex) {
		                nRow.className += aData.name;
		            },
		            fnRowCallback: function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
		                return nRow;
		            },
		            "fnDrawCallback": function (oSettings) {
		                if (oSettings.aiDisplay.length == 0) {
		                    return;
		                }
		            },
		            "aaSorting": [[0, 'asc']],
		            "sDom": 'lfr<"giveHeight"t>ip'
		        });

		    },

		    populateComponentsTable: function (id, data) {
		        $(id).empty();
		        var is_UnrefCompPresent = false;
		        $(id).append('<table id="hpsum-comps-' + data.hapi.installset.id + '-table"><thead><tr style="background-color:lightgrey;"><td><b>' +
                    Localizer.getString('hpsum.common.installSeCompOrder') + '</b></td><td><b>' +
                    Localizer.getString('hpsum.common.installSeCompAction') + '</b></td><td><b>' +
					Localizer.getString('hpsum.common.installSetCompFileName') + '</b></td><td><b>' +
					Localizer.getString('hpsum.common.installSetName') + '</b></td><td><b>' +
					Localizer.getString('hpsum.common.installSetCompVersion') + '</b></td><td><b>' +
					Localizer.getString('hpsum.common.installSetCompInstalledVersion') + '</b></td><td><b>' +
					Localizer.getString('hpsum.common.installSetCompType') + '</b></td><td><b>' +
					Localizer.getString('hpsum.common.installSetUpdatedBy') + '</b></td><td><b>' +
                    Localizer.getString('hpsum.common.installSeCompWaitTime') + '</b></td><td><b>' +
					Localizer.getString('hpsum.common.installSetCompActivates') + '</b></td><td></td><td></td></tr></thead></table>');


                //add rows to components table.               
                var currentTableId = '#hpsum-comps-' + data.hapi.installset.id + '-table';
                this.initiInstallSetComponentTable(currentTableId);
                var componentsTable = $(currentTableId).dataTable();

                if ($(currentTableId).length) {
                    componentsTable.fnClearTable();
                }
        
                if (data.hapi.hasOwnProperty('installset') && data.hapi.installset.id.match(/Unreferenced_Components/i)) {
                    $(INSTALLSET_COMPONENT_HEADER).text(Localizer.getString('hpsum.common.iLOUnrefCompDetails'));
                    is_UnrefCompPresent = true;
                }
                else {
                    $(INSTALLSET_COMPONENT_HEADER).text(Localizer.getString('hpsum.common.installSetTitle'));
                }

                var installsetComponentslist = data.hapi.installset.components;
                var installsetCompAdded = {}, installsetCompCount = 0;
                if (componentsTable && installsetComponentslist) {
                    var itemCount = 0;
                    for (var idx = 0; idx < installsetComponentslist.component.length; idx++) {
                        var currinstallsetComp = installsetComponentslist.component[idx];
                        var compAction = "";
                        if (is_UnrefCompPresent == true) {
                            compAction = Localizer.getString('hpsum.common.actionApplyUpdate');
                        }
                        else {
                            compAction = currinstallsetComp.action;
                        }
                        //add all the all teh components from install set.	
                        
                        if (installsetCompAdded[currinstallsetComp.name] != true) {
                            var installsetCompItem = [{
                                'order': ++itemCount,
                                'action': compAction,
                                'filename': currinstallsetComp.filename,
                                'name': currinstallsetComp.name,
                                'version': currinstallsetComp.version,
								'installed_version' : currinstallsetComp.installed_version,
                                'type': currinstallsetComp.type,
                                'updatedby': currinstallsetComp.updatedby,
                                'waittime' : currinstallsetComp.waittime,
                                'activates': currinstallsetComp.activates
                            }];

                            if ($(currentTableId).length) {
                                componentsTable.fnAddData(installsetCompItem);
                            }
                            installsetCompAdded[currinstallsetComp.name] = true;
                        }


                    }
                }
            },
           
            destroy: function (el) {
                $(this.element).removeClass('hpsumInstallSetComponents');
                $.removeData(this.element, "plugin_" + pluginName);
            }           
        };

		// A really lightweight plugin wrapper around the constructor,
        // preventing against multiple instantiations
        $.fn[pluginName] = function (options) {
            var instance;
            if (typeof options === 'string') {
                // call method
                var args = Array.prototype.slice.call(arguments, 1);
                this.each(function () {
                    instance = $.data(this, "plugin_" + pluginName);
                    if (!instance) {
                        if (!options.match(/destroy/i)) {
                            if (window.console) {
                                window.console.error("cannot call methods on hpInstallSetComponents prior to initialization; " +
                                    "attempted to call method '" + options + "'");
                            }
                        }
                        return;
                    }
                    if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
                        if (window.console) {
                            window.console.error("no such method '" + options + "' for hpInstallSetComponents instance");
                        }
                        return;
                    }
                    // apply method
                    instance[options].call(instance, args);
                });
            }
            else {
                return this.each(function () {
                    if (!$.data(this, "plugin_" + pluginName)) {
                        $.data(this, "plugin_" + pluginName, new Plugin(this, options));
                    }

                });
            }
        };


    } (jQuery));
});

