/*
 * 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 _pydioUtilXml = require('pydio/util/xml');

var _pydioUtilXml2 = _interopRequireDefault(_pydioUtilXml);

var _pydioModelDataModel = require('pydio/model/data-model');

var _pydioModelDataModel2 = _interopRequireDefault(_pydioModelDataModel);

var _viewsFilePreview = require('../views/FilePreview');

var _viewsFilePreview2 = _interopRequireDefault(_viewsFilePreview);

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

var muiThemeable = _require.muiThemeable;

var Color = require('color');

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

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

var Pydio = require('pydio');

var _Pydio$requireLib = Pydio.requireLib("components");

var NodeListCustomProvider = _Pydio$requireLib.NodeListCustomProvider;
var SimpleList = _Pydio$requireLib.SimpleList;

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

    function BookmarksList(props) {
        var _this = this;

        _classCallCheck(this, BookmarksList);

        _React$Component.call(this, props);

        var providerProperties = {
            get_action: "search_by_keyword",
            connexion_discrete: true,
            field: "ajxp_bookmarked"
        };
        var dataModel = _pydioModelDataModel2['default'].RemoteDataModelFactory(providerProperties, 'Notifications');
        var rNode = dataModel.getRootNode();
        rNode.observe('loading', function () {
            _this.setState({ loading: true });
        });
        rNode.observe('loaded', function () {
            _this.setState({ loading: false });
        });

        this._smObs = (function (event) {
            if (_pydioUtilXml2['default'].XPathSelectSingleNode(event, 'tree/reload_bookmarks')) {
                if (this.state.open) {
                    rNode.reload(null, true);
                } else {
                    rNode.clear();
                }
            }
        }).bind(this);
        this.props.pydio.observe("server_message", this._smObs);

        var activeRepo = undefined;
        var hasIndexer = !!_pydioUtilXml2['default'].XPathSelectSingleNode(props.pydio.getXmlRegistry(), "plugins/indexer");
        if (this.props.pydio.user && hasIndexer) {
            activeRepo = props.pydio.user.activeRepository;
        }

        this.state = {
            open: false,
            dataModel: dataModel,
            rootNode: rNode,
            activeRepository: activeRepo
        };
    }

    BookmarksList.prototype.componentWillUnmount = function componentWillUnmount() {
        if (this._smObs) {
            this.props.pydio.stopObserving("server_message", this._smObs);
        }
    };

    BookmarksList.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
        if (nextProps.pydio.user && nextProps.pydio.user.activeRepository !== this.state.activeRepository) {
            this.state.rootNode.clear();
            var hasIndexer = !!_pydioUtilXml2['default'].XPathSelectSingleNode(nextProps.pydio.getXmlRegistry(), "plugins/indexer");
            if (hasIndexer) {
                this.setState({ activeRepository: nextProps.pydio.user.activeRepository });
            } else {
                this.setState({ activeRepository: null });
            }
        }
    };

    BookmarksList.prototype.handleTouchTap = function handleTouchTap(event) {
        // This prevents ghost click.
        event.preventDefault();
        this.state.rootNode.load();
        this.setState({
            open: true,
            anchorEl: event.currentTarget
        });
    };

    BookmarksList.prototype.handleRequestClose = function handleRequestClose() {
        this.setState({
            open: false
        });
    };

    BookmarksList.prototype.renderIcon = function renderIcon(node) {
        return _react2['default'].createElement(_viewsFilePreview2['default'], {
            loadThumbnail: true,
            node: node,
            pydio: this.props.pydio,
            rounded: true
        });
    };

    BookmarksList.prototype.renderSecondLine = function renderSecondLine(node) {
        return node.getPath();
    };

    BookmarksList.prototype.entryClicked = function entryClicked(node) {
        this.handleRequestClose();
        this.props.pydio.goTo(node);
    };

    BookmarksList.prototype.render = function render() {

        if (!this.state.activeRepository) {
            return null;
        }
        var mainColor = Color(this.props.muiTheme.palette.primary1Color);
        var loader = undefined;
        if (this.state.loading) {
            loader = _react2['default'].createElement(
                'div',
                { style: { height: 200, backgroundColor: mainColor.lightness(97).rgb().toString() } },
                _react2['default'].createElement(RefreshIndicator, {
                    size: 40,
                    left: 140,
                    top: 40,
                    status: 'loading',
                    style: {}
                })
            );
        }

        return _react2['default'].createElement(
            'span',
            null,
            _react2['default'].createElement(IconButton, {
                onTouchTap: this.handleTouchTap.bind(this),
                iconClassName: "userActionIcon mdi mdi-bookmark-check",
                tooltip: this.props.pydio.MessageHash['147'],
                className: 'userActionButton'
            }),
            _react2['default'].createElement(
                Popover,
                {
                    open: this.state.open,
                    anchorEl: this.state.anchorEl,
                    anchorOrigin: { horizontal: 'left', vertical: 'bottom' },
                    targetOrigin: { horizontal: 'left', vertical: 'top' },
                    onRequestClose: this.handleRequestClose.bind(this),
                    style: { width: 320 },
                    zDepth: 2

                },
                loader,
                !this.state.loading && _react2['default'].createElement(NodeListCustomProvider, {
                    ref: 'list',
                    className: 'files-list ' + (this.props.listClassName || ''),
                    hideToolbar: true,
                    pydio: this.props.pydio,
                    elementHeight: SimpleList.HEIGHT_TWO_LINES + 2,
                    heightAutoWithMax: this.props.listOnly ? null : 500,
                    presetDataModel: this.state.dataModel,
                    reloadAtCursor: true,
                    actionBarGroups: [],
                    entryRenderIcon: this.renderIcon.bind(this),
                    entryRenderSecondLine: this.renderSecondLine.bind(this),
                    nodeClicked: this.entryClicked.bind(this),
                    emptyStateProps: _extends({
                        style: { paddingTop: 20, paddingBottom: 20 },
                        iconClassName: 'mdi mdi-bookmark-outline',
                        primaryTextId: '145',
                        secondaryTextId: '482'
                    }, this.props.emptyStateProps)
                })
            )
        );
    };

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

exports['default'] = BookmarksList = muiThemeable()(BookmarksList);
exports['default'] = BookmarksList;
module.exports = exports['default'];
