var React = require('react');
var BemMixin = require('./BemMixin');

var PropTypes = React.PropTypes;

var transformItem = function(item) {
    var bemJson = {
        block: 'menu-item',
        mods: {
            disabled: item.disabled
        },
        val: item.val,
        content: item.text
    };

    if (item.type === 'link') {
        bemJson.mods.type = 'link';
        bemJson.content = {
            block: 'link',
            url: item.url,
            content: item.text
        };
    }

    return bemJson;
};

var transformOptions = function(data) {
    return data.map(function(item) {
        if (item.group) {
            return {
                elem: 'group',
                title: item.title,
                content: item.group.map(transformItem)
            };
        }

        return transformItem(item);
    });
};

var Menu = React.createClass({
    displayName: 'Menu',
    mixins: [BemMixin],

    blockDidMount: function(block) {
        block
            .on('change', function() {
                this.callHandler('change', {
                    target: block,
                    value: block.getVal()
                });
            }.bind(this))
            .on('item-click', function(event, data) {
                this.callHandler('select', {
                    target: block,
                    value: data.item.getVal()
                });
            }.bind(this));
    }
});

// @ifdef DEBUG
Menu.propTypes = {
    disabled: PropTypes.bool,
    mod: PropTypes.string,
    mode: PropTypes.oneOf(['check', 'radio', 'radio-check']),
    onChange: PropTypes.func,
    onSelect: PropTypes.func,
    options: PropTypes.array.isRequired,
    size: PropTypes.oneOf(['s', 'm', 'l', 'xl']),
    theme: PropTypes.oneOf(['islands']),
    val: PropTypes.oneOfType([
        PropTypes.number,
        PropTypes.string,
        PropTypes.array
    ])
};
// @endif

Menu.propsMap = {
    mods: {
        disabled: null,
        mode: null,
        size: null,
        theme: null
    },
    val: [null, 'setVal'],
    options: ['content', null, transformOptions]
};

Menu.defaultProps = {
    size: 'm',
    theme: 'islands'
};

module.exports = Menu;
