/*
 * 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 _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _pydio = require('pydio');

var _pydio2 = _interopRequireDefault(_pydio);

var _WorkspaceEntry = require('./WorkspaceEntry');

var _WorkspaceEntry2 = _interopRequireDefault(_WorkspaceEntry);

var _pydioUtilXml = require('pydio/util/xml');

var _pydioUtilXml2 = _interopRequireDefault(_pydioUtilXml);

var _Pydio$requireLib = _pydio2['default'].requireLib('hoc');

var withVerticalScroll = _Pydio$requireLib.withVerticalScroll;

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

    function WorkspacesList(props, context) {
        var _this = this;

        _classCallCheck(this, WorkspacesList);

        _React$Component.call(this, props, context);
        this.state = this.stateFromPydio(props.pydio);
        this._reloadObserver = function () {
            _this.setState(_this.stateFromPydio(_this.props.pydio));
        };
    }

    WorkspacesList.prototype.stateFromPydio = function stateFromPydio(pydio) {
        return {
            workspaces: pydio.user ? pydio.user.getRepositoriesList() : [],
            showTreeForWorkspace: pydio.user ? pydio.user.activeRepository : false
        };
    };

    WorkspacesList.prototype.componentDidMount = function componentDidMount() {
        this.props.pydio.observe('repository_list_refreshed', this._reloadObserver);
    };

    WorkspacesList.prototype.componentWillUnmount = function componentWillUnmount() {
        this.props.pydio.stopObserving('repository_list_refreshed', this._reloadObserver);
    };

    WorkspacesList.prototype.createRepositoryEnabled = function createRepositoryEnabled() {
        var reg = this.props.pydio.Registry.getXML();
        return _pydioUtilXml2['default'].XPathSelectSingleNode(reg, 'actions/action[@name="user_create_repository"]') !== null;
    };

    WorkspacesList.prototype.render = function render() {
        var entries = [],
            sharedEntries = [],
            inboxEntry = undefined,
            createAction = undefined;
        var _state = this.state;
        var workspaces = _state.workspaces;
        var showTreeForWorkspace = _state.showTreeForWorkspace;
        var _props = this.props;
        var pydio = _props.pydio;
        var className = _props.className;
        var style = _props.style;
        var filterByType = _props.filterByType;

        workspaces.forEach((function (object, key) {

            if (object.getId().indexOf('ajxp_') === 0) return;
            if (object.hasContentFilter()) return;
            if (object.getAccessStatus() === 'declined') return;

            var entry = _react2['default'].createElement(_WorkspaceEntry2['default'], _extends({}, this.props, {
                key: key,
                workspace: object,
                showFoldersTree: showTreeForWorkspace && showTreeForWorkspace === key
            }));
            if (object.getAccessType() == "inbox") {
                inboxEntry = entry;
            } else if (object.getOwner()) {
                sharedEntries.push(entry);
            } else {
                entries.push(entry);
            }
        }).bind(this));

        if (inboxEntry) {
            sharedEntries.unshift(inboxEntry);
        }

        var messages = pydio.MessageHash;

        if (this.createRepositoryEnabled()) {
            var createClick = (function () {
                pydio.Controller.fireAction('user_create_repository');
            }).bind(this);
            createAction = _react2['default'].createElement(
                'div',
                { className: 'workspaces', key: 'create-action' },
                _react2['default'].createElement(
                    'div',
                    { className: 'workspace-entry', onClick: createClick, title: messages[418] },
                    _react2['default'].createElement(
                        'span',
                        { className: 'workspace-badge' },
                        '+'
                    ),
                    _react2['default'].createElement(
                        'span',
                        { className: 'workspace-label' },
                        messages[417]
                    ),
                    _react2['default'].createElement(
                        'span',
                        { className: 'workspace-description' },
                        messages[418]
                    )
                )
            );
        }

        var sections = [];
        if (entries.length) {
            sections.push({
                k: 'entries',
                title: _react2['default'].createElement(
                    'div',
                    { key: 'entries-title', className: 'section-title', style: this.props.sectionTitleStyle },
                    messages[468]
                ),
                content: _react2['default'].createElement(
                    'div',
                    { key: 'entries-ws', className: 'workspaces' },
                    entries
                )
            });
        }
        if (sharedEntries.length) {
            sections.push({
                k: 'shared',
                title: _react2['default'].createElement(
                    'div',
                    { key: 'shared-title', className: 'section-title', style: this.props.sectionTitleStyle },
                    messages[469]
                ),
                content: _react2['default'].createElement(
                    'div',
                    { key: 'shared-ws', className: 'workspaces' },
                    sharedEntries
                )
            });
        }
        if (createAction) {
            sections.push({
                k: 'create',
                title: _react2['default'].createElement('div', { key: 'create-title', className: 'section-title', style: this.props.sectionTitleStyle }),
                content: createAction
            });
        }

        var classNames = ['user-workspaces-list'];
        if (className) classNames.push(className);

        if (filterByType) {
            var ret = undefined;
            sections.map(function (s) {
                if (filterByType && filterByType === s.k) {
                    ret = _react2['default'].createElement(
                        'div',
                        { className: classNames.join(' '), style: style },
                        s.title,
                        s.content
                    );
                }
            });
            return ret;
        }

        var elements = [];
        sections.map(function (s) {
            elements.push(s.title);
            elements.push(s.content);
        });
        return _react2['default'].createElement(
            'div',
            { className: classNames.join(' '), style: style },
            elements
        );
    };

    return WorkspacesList;
})(_react2['default'].Component);

WorkspacesList.PropTypes = {
    pydio: _react2['default'].PropTypes.instanceOf(_pydio2['default']),
    workspaces: _react2['default'].PropTypes.instanceOf(Map),
    showTreeForWorkspace: _react2['default'].PropTypes.string,
    onHoverLink: _react2['default'].PropTypes.func,
    onOutLink: _react2['default'].PropTypes.func,
    className: _react2['default'].PropTypes.string,
    style: _react2['default'].PropTypes.object,
    sectionTitleStyle: _react2['default'].PropTypes.object,
    filterByType: _react2['default'].PropTypes.oneOf(['shared', 'entries', 'create'])
};

exports['default'] = WorkspacesList = withVerticalScroll(WorkspacesList);

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