/*
 * Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
 * This file is part of Pydio.
 *
 * Pydio is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Pydio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Pydio.  If not, see <http://www.gnu.org/licenses/>.
 *
 * The latest code can be found at <https://pydio.com>.
 */

'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _avatarUserAvatar = require('../avatar/UserAvatar');

var _avatarUserAvatar2 = _interopRequireDefault(_avatarUserAvatar);

var _viewsEmptyStateView = require('../../views/EmptyStateView');

var _viewsEmptyStateView2 = _interopRequireDefault(_viewsEmptyStateView);

var _AlphaPaginator = require('./AlphaPaginator');

var _AlphaPaginator2 = _interopRequireDefault(_AlphaPaginator);

var _SearchForm = require('./SearchForm');

var _SearchForm2 = _interopRequireDefault(_SearchForm);

var _require = require('material-ui');

var IconButton = _require.IconButton;
var Checkbox = _require.Checkbox;
var FlatButton = _require.FlatButton;
var RaisedButton = _require.RaisedButton;
var ListItem = _require.ListItem;
var FontIcon = _require.FontIcon;
var Avatar = _require.Avatar;
var Divider = _require.Divider;
var Subheader = _require.Subheader;
var List = _require.List;

var _require2 = require('material-ui/styles');

var muiThemeable = _require2.muiThemeable;

var _require$requireLib = require('pydio').requireLib('boot');

var Loader = _require$requireLib.Loader;
var PydioContextConsumer = _require$requireLib.PydioContextConsumer;

var UsersList = (function (_React$Component) {
    _inherits(UsersList, _React$Component);

    function UsersList(props, context) {
        _classCallCheck(this, UsersList);

        _React$Component.call(this, props, context);
        this.state = { select: false, selection: [] };
    }

    UsersList.prototype.render = function render() {
        var _this = this;

        var _props = this.props;
        var item = _props.item;
        var mode = _props.mode;
        var paginatorType = _props.paginatorType;
        var loading = _props.loading;
        var enableSearch = _props.enableSearch;
        var showSubheaders = _props.showSubheaders;
        var getMessage = _props.getMessage;

        var folders = item.collections || [];
        var leafs = item.leafs || [];
        var foldersSubHeader = folders.length && (leafs.length || showSubheaders) ? [{ subheader: getMessage('532') }] : [];
        var usersSubHeader = [];
        if ((showSubheaders || paginatorType) && leafs.length) {
            usersSubHeader = [{ subheader: paginatorType ? React.createElement(_AlphaPaginator2['default'], _extends({}, this.props, { style: { lineHeight: '20px', padding: '14px 0' } })) : getMessage('249') }];
        }
        var items = [].concat(foldersSubHeader, folders, usersSubHeader, leafs);
        var total = items.length;
        var elements = [];
        var toggleSelect = function toggleSelect() {
            _this.setState({ select: !_this.state.select, selection: [] });
        };
        var createAction = function createAction() {
            _this.props.onCreateAction(item);
        };
        var deleteAction = function deleteAction() {
            _this.props.onDeleteAction(item, _this.state.selection);_this.setState({ select: false, selection: [] });
        };

        var activeTbarColor = this.props.muiTheme.palette.accent2Color;
        var toolbar = React.createElement(
            'div',
            { style: { padding: 10, height: 56, backgroundColor: this.state.select ? activeTbarColor : '#fafafa', display: 'flex', alignItems: 'center', transition: DOMUtils.getBeziersTransition() } },
            mode === "selector" && item._parent && React.createElement(IconButton, { iconClassName: 'mdi mdi-chevron-left', onTouchTap: function () {
                    _this.props.onFolderClicked(item._parent);
                } }),
            mode === 'book' && total > 0 && item.actions && item.actions.multiple && React.createElement(Checkbox, { style: { width: 'initial', marginLeft: this.state.select ? 7 : 14 }, checked: this.state.select, onCheck: toggleSelect }),
            React.createElement(
                'div',
                { style: { flex: 1, fontSize: 20, color: this.state.select ? 'white' : 'rgba(0,0,0,0.87)' } },
                item.label
            ),
            mode === 'book' && item.actions && item.actions.create && !this.state.select && React.createElement(FlatButton, { secondary: true, label: getMessage(item.actions.create), onTouchTap: createAction }),
            mode === 'book' && item.actions && item.actions.remove && this.state.select && React.createElement(RaisedButton, { secondary: true, label: getMessage(item.actions.remove), disabled: !this.state.selection.length, onTouchTap: deleteAction }),
            enableSearch && React.createElement(_SearchForm2['default'], { searchLabel: this.props.searchLabel, onSearch: this.props.onSearch, style: { flex: 1, minWidth: 200 } })
        );
        // PARENT NODE
        if (item._parent && mode === 'book' && item._parent._parent) {
            elements.push(React.createElement(ListItem, {
                key: '__parent__',
                primaryText: "..",
                onTouchTap: function (e) {
                    e.stopPropagation();_this.props.onFolderClicked(item._parent);
                },
                leftAvatar: React.createElement(Avatar, { icon: React.createElement(FontIcon, { className: 'mdi mdi-arrow-up' }) })
            }));
            if (total) {
                elements.push(React.createElement(Divider, { inset: true, key: 'parent-divider' }));
            }
        }
        // ITEMS
        items.forEach((function (item, index) {
            var _this2 = this;

            if (item.subheader) {
                elements.push(React.createElement(
                    Subheader,
                    null,
                    item.subheader
                ));
                return;
            }
            var fontIcon = React.createElement(_avatarUserAvatar2['default'], { avatarSize: 36, pydio: this.props.pydio || pydio,
                userId: item.id,
                userLabel: item.label,
                avatar: item.avatar,
                icon: item.icon,
                avatarOnly: true,
                useDefaultAvatar: true
            });
            var rightIconButton = undefined;
            var touchTap = function touchTap(e) {
                e.stopPropagation();_this2.props.onItemClicked(item);
            };
            if (folders.indexOf(item) > -1 && this.props.onFolderClicked) {
                touchTap = function (e) {
                    e.stopPropagation();_this2.props.onFolderClicked(item);
                };
                if (mode === 'selector' && !item._notSelectable) {
                    rightIconButton = React.createElement(IconButton, {
                        iconClassName: "mdi mdi-account-multiple-plus",
                        tooltip: "Select this group",
                        tooltipPosition: 'bottom-left',
                        onTouchTap: function () {
                            _this2.props.onItemClicked(item);
                        }
                    });
                }
            } else if (mode === 'inner' && this.props.onDeleteAction) {
                rightIconButton = React.createElement(IconButton, {
                    iconClassName: "mdi mdi-delete",
                    tooltip: getMessage(257),
                    tooltipPosition: 'bottom-left',
                    iconStyle: { color: 'rgba(0,0,0,0.13)', hoverColor: 'rgba(0,0,0,0.53)' },
                    onTouchTap: function () {
                        _this2.props.onDeleteAction(_this2.props.item, [item]);
                    }
                });
            }
            var select = function select(e, checked) {
                if (checked) {
                    _this2.setState({ selection: [].concat(_this2.state.selection, [item]) });
                } else {
                    var stateSel = _this2.state.selection;
                    var selection = [].concat(stateSel.slice(0, stateSel.indexOf(item)), stateSel.slice(stateSel.indexOf(item) + 1));
                    _this2.setState({ selection: selection });
                }
            };
            elements.push(React.createElement(ListItem, {
                key: item.id,
                primaryText: item.label,
                onTouchTap: touchTap,
                disabled: mode === 'inner',
                leftAvatar: !this.state.select && fontIcon,
                rightIconButton: rightIconButton,
                leftCheckbox: this.state.select && React.createElement(Checkbox, { checked: this.state.selection.indexOf(item) > -1, onCheck: select })
            }));
            if (mode !== 'inner' && index < total - 1) {
                elements.push(React.createElement(Divider, { inset: true, key: item.id + '-divider' }));
            }
        }).bind(this));

        var emptyState = undefined;
        if (!elements.length) {
            var emptyStateProps = {
                style: { backgroundColor: 'rgb(250, 250, 250)' },
                iconClassName: 'mdi mdi-account-off',
                primaryTextId: this.props.emptyStatePrimaryText || getMessage(629),
                secondaryTextId: mode === 'book' ? this.props.emptyStateSecondaryText || null : null
            };
            if (mode === 'book' && item.actions && item.actions.create) {
                emptyStateProps = _extends({}, emptyStateProps, {
                    actionLabelId: getMessage(item.actions.create),
                    actionCallback: createAction
                });
            }
            emptyState = React.createElement(_viewsEmptyStateView2['default'], emptyStateProps);
        }

        return React.createElement(
            'div',
            { style: { flex: 1, flexDirection: 'column', display: 'flex' }, onTouchTap: this.props.onTouchTap },
            mode !== 'inner' && /*(!emptyState || mode !== 'book') &&*/!this.props.noToolbar && toolbar,
            !emptyState && !loading && React.createElement(
                List,
                { style: { flex: 1, overflowY: mode !== 'inner' ? 'auto' : 'initial' } },
                this.props.subHeader && React.createElement(
                    Subheader,
                    null,
                    this.props.subHeader
                ),
                elements
            ),
            loading && React.createElement(Loader, { style: { flex: 1 } }),
            !loading && emptyState
        );
    };

    return UsersList;
})(React.Component);

UsersList.propTypes = {
    item: React.PropTypes.object,
    onCreateAction: React.PropTypes.func,
    onDeleteAction: React.PropTypes.func,
    onItemClicked: React.PropTypes.func,
    onFolderClicked: React.PropTypes.func,
    mode: React.PropTypes.oneOf(['book', 'selector', 'inner'])
};

exports['default'] = UsersList = PydioContextConsumer(UsersList);
exports['default'] = UsersList = muiThemeable()(UsersList);

exports['default'] = UsersList;
module.exports = exports['default'];
