'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 SortByItem(_ref) {
	var option = _ref.option,
	    index = _ref.index,
	    id = _ref.id;

	return _react2.default.createElement(
		_reactBootstrap.MenuItem,
		{
			id: id && id + '-by-item-' + option.id,
			key: index,
			eventKey: option
		},
		option.name || option.id
	);
}
SortByItem.propTypes = {
	option: _react.PropTypes.shape({
		id: _react.PropTypes.string,
		name: _react.PropTypes.string
	}),
	index: _react.PropTypes.number,
	id: _react.PropTypes.string
};

function SelectSortBy(_ref2) {
	var field = _ref2.field,
	    id = _ref2.id,
	    isDescending = _ref2.isDescending,
	    onChange = _ref2.onChange,
	    options = _ref2.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 });
	}

	var getMenuItem = SortByItem;
	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,
				className: _SelectSortBy2.default['sort-by-items']
			},
			options.map(function (option, index) {
				return getMenuItem({
					option: option,
					index: index,
					id: id
				});
			})
		),
		selected && _react2.default.createElement(
			_reactBootstrap.NavItem,
			{
				id: id && id + '-order',
				onClick: onChangeOrder
			},
			order ? 'Descending' : 'Ascending'
		)
	);
}

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

exports.default = SelectSortBy;