/*
 * 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;

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 _addressbookAddressBook = require('../addressbook/AddressBook');

var _addressbookAddressBook2 = _interopRequireDefault(_addressbookAddressBook);

var React = require('react');

var _require = require('pydio/http/users-api');

var UsersApi = _require.UsersApi;

var ResourcesManager = require('pydio/http/resources-manager');

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

var IconButton = _require2.IconButton;
var Popover = _require2.Popover;

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

var muiThemeable = _require3.muiThemeable;

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

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

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

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

        _React$Component.call(this, props, context);
        this.state = { showPicker: false, pickerAnchor: null, showMailer: false, mailerAnchor: null };
    }

    ActionsPanel.prototype.onTeamSelected = function onTeamSelected(item) {
        this.setState({ showPicker: false });
        if (item.getType() === 'group' && item.getId().indexOf('/AJXP_TEAM/') === 0) {
            UsersApi.addUserToTeam(item.getId().replace('/AJXP_TEAM/', ''), this.props.userId, this.props.reloadAction);
        }
    };

    ActionsPanel.prototype.onUserSelected = function onUserSelected(item) {
        this.setState({ showPicker: false });
        UsersApi.addUserToTeam(this.props.team.id, item.getId(), this.props.reloadAction);
    };

    ActionsPanel.prototype.openPicker = function openPicker(event) {
        this.setState({ showPicker: true, pickerAnchor: event.currentTarget });
    };

    ActionsPanel.prototype.openMailer = function openMailer(event) {
        var _this = this;

        var target = event.currentTarget;
        ResourcesManager.loadClassesAndApply(['PydioMailer'], function () {
            _this.setState({ mailerLibLoaded: true }, function () {
                _this.setState({ showMailer: true, mailerAnchor: target });
            });
        });
    };

    ActionsPanel.prototype.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
        if (!this.props.lockOnSubPopoverOpen) return;
        if ((this.state.showPicker || this.state.showMailer) && !(prevState.showPicker || prevState.showMailer)) {
            this.props.lockOnSubPopoverOpen(true);
        } else if (!(this.state.showPicker || this.state.showMailer) && (prevState.showPicker || prevState.showMailer)) {
            this.props.lockOnSubPopoverOpen(false);
        }
    };

    ActionsPanel.prototype.render = function render() {
        var _this2 = this;

        var _props = this.props;
        var getMessage = _props.getMessage;
        var muiTheme = _props.muiTheme;
        var team = _props.team;
        var user = _props.user;
        var userEditable = _props.userEditable;

        var styles = {
            button: {
                backgroundColor: muiTheme.palette.accent2Color,
                borderRadius: '50%',
                margin: '0 4px',
                width: 44,
                height: 44,
                padding: 10
            },
            icon: {
                color: 'white'
            }
        };
        var mailer = undefined,
            usermails = {};
        var actions = [];
        if (user && user.hasEmail) {
            actions.push({ key: 'message', label: getMessage(598), icon: 'email', callback: this.openMailer.bind(this) });
            usermails[this.props.user.id] = PydioUsers.User.fromObject(this.props.user);
        }
        if (team) {
            actions.push({ key: 'users', label: getMessage(599), icon: 'account-multiple-plus', callback: this.openPicker.bind(this) });
        } else {
            actions.push({ key: 'teams', label: getMessage(573), icon: 'account-multiple-plus', callback: this.openPicker.bind(this) });
        }
        if (userEditable) {
            actions.push({ key: 'edit', label: this.props.team ? getMessage(580) : getMessage(600), icon: 'pencil', callback: this.props.onEditAction });
            actions.push({ key: 'delete', label: this.props.team ? getMessage(570) : getMessage(582), icon: 'delete', callback: this.props.onDeleteAction });
        }

        return React.createElement(
            'div',
            { style: { textAlign: 'center', marginBottom: 16 } },
            actions.map(function (a) {
                return React.createElement(IconButton, {
                    key: a.key,
                    style: styles.button,
                    iconStyle: styles.icon,
                    tooltip: a.label,
                    iconClassName: "mdi mdi-" + a.icon,
                    onTouchTap: a.callback
                });
            }),
            React.createElement(
                Popover,
                {
                    open: this.state.showPicker,
                    anchorEl: this.state.pickerAnchor,
                    anchorOrigin: { horizontal: 'right', vertical: 'top' },
                    targetOrigin: { horizontal: 'right', vertical: 'top' },
                    onRequestClose: function () {
                        _this2.setState({ showPicker: false });
                    },
                    useLayerForClickAway: false,
                    style: { zIndex: 2200 }
                },
                React.createElement(
                    'div',
                    { style: { width: 256, height: 320 } },
                    React.createElement(_addressbookAddressBook2['default'], {
                        mode: 'selector',
                        pydio: this.props.pydio,
                        loaderStyle: { width: 320, height: 420 },
                        onItemSelected: this.props.team ? this.onUserSelected.bind(this) : this.onTeamSelected.bind(this),
                        teamsOnly: this.props.team ? false : true,
                        usersOnly: this.props.team ? true : false
                    })
                )
            ),
            React.createElement(
                Popover,
                {
                    open: this.state.showMailer,
                    anchorEl: this.state.mailerAnchor,
                    anchorOrigin: { horizontal: 'right', vertical: 'top' },
                    targetOrigin: { horizontal: 'right', vertical: 'top' },
                    useLayerForClickAway: false,
                    style: { zIndex: 2200 }
                },
                React.createElement(
                    'div',
                    { style: { width: 256, height: 320 } },
                    this.state.mailerLibLoaded && React.createElement(AsyncComponent, {
                        namespace: 'PydioMailer',
                        componentName: 'Pane',
                        zDepth: 0,
                        panelTitle: getMessage(598),
                        uniqueUserStyle: true,
                        users: usermails,
                        onDismiss: function () {
                            _this2.setState({ showMailer: false });
                        },
                        onFieldFocus: this.props.otherPopoverMouseOver
                    })
                )
            )
        );
    };

    return ActionsPanel;
})(React.Component);

ActionsPanel.propTypes = {

    /**
     * User data, props must pass at least one of 'user' or 'team'
     */
    user: React.PropTypes.object,
    /**
     * Team data, props must pass at least one of 'user' or 'team'
     */
    team: React.PropTypes.object,
    /**
     * For users, whether it is editable or not
     */
    userEditable: React.PropTypes.object

};

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

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