import React from 'react';
import BemMenu from 'react-bem-components/lib/Menu';

import './index.css';

const Menu = React.createClass({

    getElement() {
        return this._element;
    },

    getItemGroups() {
        return this._groups;
    },

    _postrender(element) {
        if (!element) {
            return;
        }

        const items = element.block.getItems();

        if (!this.props.options || !items) {
            return;
        }

        let flatOptions = [];

        this.props.options.forEach(option => {
            if (option.group) {
                flatOptions = flatOptions.concat(option.group);
            } else {
                flatOptions.push(option);
            }
        });

        items.forEach((item, index) => {
            const option = flatOptions[index];

            if (option.type) {
                item.domElem.addClass(`menu-item__${option.type}`);
            }

            if (option.icon) {
                const iconStyle = `background-image: url(${option.icon});`;

                item.domElem
                    .wrapInner('<div class="menu-item__content"/>')
                    .prepend(`<div class="menu-item__icon" style="${iconStyle}"/>`);
            }
        });

        this._element = element.block.domElem;
        this._groups = element.block.elem('group');
    },

    render() {
        return (
            <BemMenu {...this.props} ref={this._postrender} />
        );
    },
});

export default Menu;
