/**
 * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org)  Apache License, Version 2.0  http://www.apache.org/licenses/LICENSE-2.0
 */
define(['lodash', 'event_channel', 'menu_item'],
    function (_, EventChannel, MenuItem){

        var MenuGroup = function(args){
            _.assign(this, args);
        };

        MenuGroup.prototype = Object.create(EventChannel.prototype);
        MenuGroup.prototype.constructor = MenuGroup;

        MenuGroup.prototype.render = function(){

            var menuItemDefinitions = _.get(this, 'definition.items');
            var parent = _.get(this, 'options.parent');
            var menuItemOpts = _.cloneDeep(_.get(this, 'options.menu_item'));

            var toolBarDiv = $('<div></div>');
            toolBarDiv.attr('id', _.get(this, 'definition.label'));
            toolBarDiv.addClass(_.get(this, 'options.cssClass.group'));
            parent.append(toolBarDiv);

            var title = $('<a></a>');
            title.text(_.get(this, 'definition.label'));
            title.addClass(_.get(this, 'options.cssClass.toggle'));
            title.attr("data-toggle", "dropdown");
            title.on('mouseover', function(e){
                var thisElem = $(e.target).parent();
                var toggleClass = 'open';
                _.some(thisElem.siblings(), function (el) {
                    if($(el).hasClass(toggleClass)){
                        thisElem.addClass(toggleClass);
                        $(el).removeClass(toggleClass);
                        return;
                    }
                });
            });
            toolBarDiv.append(title);

            var menu = $('<ul></ul>');
            menu.addClass(_.get(this, 'options.cssClass.menu'));
            toolBarDiv.append(menu);

            var self = this;

            //Iterate over menu items
            _.forEach(menuItemDefinitions, function (menuItemDef) {

                var menuItemOptions = {definition: _.cloneDeep(menuItemDef)};
                _.set(menuItemOptions, 'options', menuItemOpts);
                _.set(menuItemOptions, 'options.parent', menu);
                _.set(menuItemOptions, 'options.application', _.get(self, 'options.application'));
                var menuItem = new MenuItem(menuItemOptions);
                menuItem.render();
                _.set(self, menuItem.getID(), menuItem);
            });
        };

        MenuGroup.prototype.getID = function(){
            return _.get(this, 'definition.id');
        };

        return MenuGroup;

    });