'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactBootstrap = require('react-bootstrap');

var _uuid = require('uuid');

var _uuid2 = _interopRequireDefault(_uuid);

var _SelectSortBy = require('./SelectSortBy.scss');

var _SelectSortBy2 = _interopRequireDefault(_SelectSortBy);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function SelectSortBy(_ref) {
	var field = _ref.field,
	    id = _ref.id,
	    isDescending = _ref.isDescending,
	    onChange = _ref.onChange,
	    options = _ref.options;

	var order = isDescending || false;
	var selected = field && options.find(function (item) {
		return item.id === field;
	});

	function onChangeField(newField, event) {
		return onChange(event, { field: newField.id, isDescending: order });
	}

	function onChangeOrder(event) {
		return onChange(event, { field: selected.id, isDescending: !order });
	}

	function getMenuItem(option, index) {
		return _react2.default.createElement(
			_reactBootstrap.MenuItem,
			{
				id: id && id + '-by-item-' + option.id,
				key: index,
				eventKey: option
			},
			option.name || option.id
		);
	}

	return _react2.default.createElement(
		_reactBootstrap.Nav,
		{ className: _SelectSortBy2.default['tc-list-toolbar-sort-by'] },
		options.length === 1 ? _react2.default.createElement(
			'li',
			{ className: 'navbar-text' },
			options[0].name
		) : _react2.default.createElement(
			_reactBootstrap.NavDropdown,
			{
				id: id ? id + '-by' : _uuid2.default.v4(),
				title: selected ? selected.name || selected.id : 'N.C',
				onSelect: onChangeField
			},
			options.map(function (option, index) {
				return getMenuItem(option, index, id);
			})
		),
		selected && _react2.default.createElement(
			_reactBootstrap.NavItem,
			{
				id: id && id + '-order',
				onClick: onChangeOrder
			},
			order ? 'DESCENDING' : 'ASCENDING'
		)
	);
}

SelectSortBy.propTypes = {
	field: _react2.default.PropTypes.string,
	id: _react2.default.PropTypes.string,
	isDescending: _react2.default.PropTypes.bool,
	onChange: _react2.default.PropTypes.func.isRequired,
	options: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.shape({
		id: _react2.default.PropTypes.string.isRequired,
		name: _react2.default.PropTypes.string
	})).isRequired
};

exports.default = SelectSortBy;