/*
 * 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 _managerManager = require('../manager/Manager');

var _managerManager2 = _interopRequireDefault(_managerManager);

var _FormPanel = require('./FormPanel');

var _FormPanel2 = _interopRequireDefault(_FormPanel);

var React = require('react');

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

var Paper = _require.Paper;
var FlatButton = _require.FlatButton;
var Divider = _require.Divider;

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

var User = _require2.User;
var UsersApi = _require2.UsersApi;

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

    UserCreationForm.prototype.getCreateUserParameters = function getCreateUserParameters() {
        var editMode = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0];

        var basicParameters = [];
        var pydio = this.props.pydio;
        var MessageHash = pydio.MessageHash;

        var prefix = pydio.getPluginConfigs('action.share').get('SHARED_USERS_TMP_PREFIX');
        basicParameters.push({
            description: MessageHash['533'],
            editable: false,
            expose: "true",
            label: MessageHash['522'],
            name: editMode ? "existing_user_id" : "new_user_id",
            scope: "user",
            type: editMode ? "hidden" : "string",
            mandatory: "true",
            "default": prefix ? prefix : ''
        }, {
            description: MessageHash['534'],
            editable: "true",
            expose: "true",
            label: MessageHash['523'],
            name: "new_password",
            scope: "user",
            type: "valid-password",
            mandatory: "true"
        });

        var params = global.pydio.getPluginConfigs('conf').get('NEWUSERS_EDIT_PARAMETERS').split(',');
        for (var i = 0; i < params.length; i++) {
            params[i] = "user/preferences/pref[@exposed]|//param[@name='" + params[i] + "']";
        }
        var xPath = params.join('|');
        _managerManager2['default'].parseParameters(this.props.pydio.getXmlRegistry(), xPath).map(function (el) {
            basicParameters.push(el);
        });
        if (!editMode) {
            basicParameters.push({
                description: MessageHash['536'],
                editable: "true",
                expose: "true",
                label: MessageHash['535'],
                name: "send_email",
                scope: "user",
                type: "boolean",
                mandatory: true
            });
        }
        return basicParameters;
    };

    UserCreationForm.prototype.getDefaultProps = function getDefaultProps() {
        return { editMode: false };
    };

    UserCreationForm.prototype.getParameters = function getParameters() {
        if (!this._parsedParameters) {
            this._parsedParameters = this.getCreateUserParameters(this.props.editMode);
        }
        return this._parsedParameters;
    };

    UserCreationForm.prototype.getValuesForPost = function getValuesForPost(prefix) {
        return _managerManager2['default'].getValuesForPOST(this.getParameters(), this.state.values, prefix);
    };

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

        _React$Component.call(this, props, context);

        var _props = this.props;
        var pydio = _props.pydio;
        var newUserName = _props.newUserName;
        var editMode = _props.editMode;
        var userData = _props.userData;

        var userPrefix = pydio.getPluginConfigs('action.share').get('SHARED_USERS_TMP_PREFIX');
        if (!userPrefix || newUserName.startsWith(userPrefix)) userPrefix = '';
        var idKey = editMode ? 'existing_user_id' : 'new_user_id';
        var values = {
            new_password: '',
            send_email: true
        };
        if (editMode) {
            values['existing_user_id'] = this.props.newUserName;
            if (userData) {
                values['lang'] = userData.lang;
                values[userPrefix + 'USER_DISPLAY_NAME'] = userData.USER_DISPLAY_NAME;
                values[userPrefix + 'email'] = userData.email;
            }
        } else {
            values['new_user_id'] = userPrefix + newUserName;
            values['lang'] = pydio.currentLanguage;
        }
        this.state = { values: values, valid: false };
    }

    UserCreationForm.prototype.onValuesChange = function onValuesChange(newValues) {
        this.setState({ values: newValues });
    };

    UserCreationForm.prototype.submitCreationForm = function submitCreationForm() {

        var prefix = 'NEW_';
        var values = this.getValuesForPost(prefix);
        UsersApi.createUserFromPost(values, (function (values, jsonReponse) {
            var id = undefined;
            if (jsonReponse['createdUserId']) {
                id = jsonReponse['createdUserId'];
            } else {
                id = values[prefix + 'new_user_id'];
            }
            var display = values[prefix + 'USER_DISPLAY_NAME'] || id;
            var fakeUser = new User(id, display, 'user');
            this.props.onUserCreated(fakeUser);
        }).bind(this));
    };

    UserCreationForm.prototype.cancelCreationForm = function cancelCreationForm() {
        this.props.onCancel();
    };

    UserCreationForm.prototype.changeValidStatus = function changeValidStatus(status) {
        this.setState({ valid: status });
    };

    UserCreationForm.prototype.render = function render() {
        var pydio = this.props.pydio;
        var status = this.state.valid;
        if (!status && this.props.editMode && !this.state.values['new_password']) {
            status = true;
        }
        return React.createElement(
            Paper,
            { zDepth: this.props.zDepth !== undefined ? this.props.zDepth : 2, style: _extends({ height: 250, display: 'flex', flexDirection: 'column' }, this.props.style) },
            React.createElement(_FormPanel2['default'], {
                className: 'reset-pydio-forms',
                depth: -1,
                parameters: this.getParameters(),
                values: this.state.values,
                onChange: this.onValuesChange.bind(this),
                onValidStatusChange: this.changeValidStatus.bind(this),
                style: { overflowY: 'auto', flex: 1 }
            }),
            React.createElement(Divider, { style: { flexShrink: 0 } }),
            React.createElement(
                'div',
                { style: { padding: 8, textAlign: 'right' } },
                React.createElement(FlatButton, { label: pydio.MessageHash[49], onTouchTap: this.cancelCreationForm.bind(this) }),
                React.createElement(FlatButton, { label: this.props.editMode ? pydio.MessageHash[519] : pydio.MessageHash[484], secondary: true, onTouchTap: this.submitCreationForm.bind(this), disabled: !status })
            )
        );
    };

    return UserCreationForm;
})(React.Component);

UserCreationForm.propTypes = {
    newUserName: React.PropTypes.string,
    onUserCreated: React.PropTypes.func.isRequired,
    onCancel: React.PropTypes.func.isRequired,
    onValidStatusChange: React.PropTypes.func,
    editMode: React.PropTypes.bool,
    userData: React.PropTypes.object
};

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