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

var React = require('react');

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

var ActionDialogMixin = _require$requireLib.ActionDialogMixin;
var CancelButtonProviderMixin = _require$requireLib.CancelButtonProviderMixin;
var SubmitButtonProviderMixin = _require$requireLib.SubmitButtonProviderMixin;
var Loader = _require$requireLib.Loader;

var PydioApi = require('pydio/http/api');
var XMLUtils = require('pydio/util/xml');

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

var Divider = _require.Divider;
var List = _require.List;
var ListItem = _require.ListItem;
var FlatButton = _require.FlatButton;

/**
 * Dialog for letting users create a workspace
 */
exports['default'] = React.createClass({
    displayName: 'CreateRepositoryDialog',

    mixins: [ActionDialogMixin, CancelButtonProviderMixin, SubmitButtonProviderMixin],

    getDefaultProps: function getDefaultProps() {
        return {
            dialogTitleId: '418',
            dialogIsModal: true,
            dialogScrollBody: true,
            dialogPadding: 0
        };
    },

    getInitialState: function getInitialState() {
        return { xmlDefinitions: null, templateId: null, formParameters: null, formValues: {}, formLoaded: false, formValid: false };
    },

    getButtons: function getButtons() {
        var updater = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];

        if (updater !== null) {
            this._updater = updater;
        }
        var _state = this.state;
        var templateId = _state.templateId;
        var formValid = _state.formValid;

        var buttons = [];
        if (templateId) {
            buttons.push(React.createElement(FlatButton, { style: { float: 'left' }, label: '<<', onTouchTap: this.resetTemplate.bind(this) }));
        }
        buttons.push(React.createElement(FlatButton, { label: 'Cancel', onTouchTap: this.props.onDismiss }));
        buttons.push(React.createElement(FlatButton, { secondary: true, label: 'OK', disabled: !formValid, onTouchTap: this.submit.bind(this) }));
        return buttons;
    },

    componentDidMount: function componentDidMount() {
        var _this = this;

        require('pydio').requireLib('form', true).then(function () {
            _this.setState({ formLoaded: true });
        });

        PydioApi.getClient().request({ get_action: 'get_user_templates_definition' }, function (transport) {
            _this.setState({ xmlDefinitions: transport.responseXML });
        });
        return;
    },

    submit: function submit() {
        var _this2 = this;

        var _state2 = this.state;
        var xmlDefinitions = _state2.xmlDefinitions;
        var templateId = _state2.templateId;
        var formParameters = _state2.formParameters;
        var formValues = _state2.formValues;
        var formLoaded = _state2.formLoaded;

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

        var Manager = _require$requireLib2.Manager;

        var parameters = Manager.parseParameters(xmlDefinitions, '//template[@repository_id="' + templateId + '"]/param');
        var postValues = Manager.getValuesForPOST(parameters, formValues, 'DRIVER_OPTION_');
        if (postValues['DRIVER_OPTION_DISPLAY']) {
            postValues['DISPLAY'] = postValues['DRIVER_OPTION_DISPLAY'];
            delete postValues['DRIVER_OPTION_DISPLAY'], delete postValues['DRIVER_OPTION_DISPLAY_ajxptype'];
        } else {
            postValues['DISPLAY'] = "NEW REPOSITORY TEST";
        }
        PydioApi.getClient().request(_extends({
            get_action: 'user_create_repository',
            template_id: templateId
        }, postValues), function (transport) {
            _this2.dismiss();
        });
    },

    chooseTemplate: function chooseTemplate(templateId) {
        var _this3 = this;

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

        var Manager = _require$requireLib3.Manager;
        var xmlDefinitions = this.state.xmlDefinitions;

        var parameters = Manager.parseParameters(xmlDefinitions, '//template[@repository_id="' + templateId + '"]/param');
        var displayParamIndex = parameters.findIndex(function (p) {
            return p.name === 'DISPLAY';
        });
        if (displayParamIndex > -1) {
            var displayParam = parameters[displayParamIndex];
            parameters.splice(displayParamIndex, 1);
            parameters.unshift(displayParam);
        }
        this.setState({
            templateId: templateId,
            formParameters: parameters
        }, function () {
            _this3._updater(_this3.getButtons());
        });
    },

    resetTemplate: function resetTemplate() {
        var _this4 = this;

        this.setState({
            templateId: null,
            formParameters: null,
            formValues: {},
            formValid: false
        }, function () {
            _this4._updater(_this4.getButtons());
        });
    },

    onFormValidStatusChange: function onFormValidStatusChange(newValidValue, failedFields) {
        var _this5 = this;

        this.setState({ formValid: newValidValue }, function () {
            _this5._updater(_this5.getButtons());
        });
    },

    render: function render() {
        var _this6 = this;

        var _state3 = this.state;
        var xmlDefinitions = _state3.xmlDefinitions;
        var templateId = _state3.templateId;
        var formParameters = _state3.formParameters;
        var formValues = _state3.formValues;
        var formLoaded = _state3.formLoaded;
        var MessageHash = this.props.pydio.MessageHash;

        if (!xmlDefinitions || !formLoaded) {
            return React.createElement(Loader, null);
        }
        if (!templateId) {
            var templates = XMLUtils.XPathSelectNodes(xmlDefinitions, "//template");
            var items = [];

            var _loop = function (i) {
                var label = templates[i].getAttribute('repository_label');
                var tplId = templates[i].getAttribute('repository_id');
                items.push(React.createElement(ListItem, { key: tplId, primaryText: label, onTouchTap: function () {
                        return _this6.chooseTemplate(tplId);
                    } }));
                if (i < templates.length - 1) {
                    items.push(React.createElement(Divider, { key: tplId + '-divider' }));
                }
            };

            for (var i = 0; i < templates.length; i++) {
                _loop(i);
            }
            return React.createElement(
                'div',
                { style: { width: '100%' } },
                React.createElement(
                    'p',
                    { style: { padding: 16, paddingBottom: 0, marginBottom: 0, color: 'rgba(0,0,0,.43)' } },
                    MessageHash['420']
                ),
                React.createElement(
                    List,
                    null,
                    items
                )
            );
        }

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

        var FormPanel = _require$requireLib4.FormPanel;

        return React.createElement(
            'div',
            { style: { width: '100%' } },
            React.createElement(FormPanel, {
                depth: -2,
                parameters: formParameters,
                values: formValues,
                onChange: function (newValues) {
                    _this6.setState({ formValues: newValues });
                },
                onValidStatusChange: this.onFormValidStatusChange.bind(this)
            })
        );

        return React.createElement('div', null);
    }

});
module.exports = exports['default'];
