/*
 * 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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var Loaders = (function () {
    function Loaders() {
        _classCallCheck(this, Loaders);
    }

    Loaders.childrenAsPromise = function childrenAsPromise(item) {
        var leaf = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
        var childrenLoader = item.childrenLoader;
        var itemsLoader = item.itemsLoader;
        var leafLoaded = item.leafLoaded;
        var collectionsLoaded = item.collectionsLoaded;
        var leafs = item.leafs;
        var collections = item.collections;

        var loader = leaf ? itemsLoader : childrenLoader;
        var loaded = leaf ? leafLoaded : collectionsLoaded;
        return new Promise(function (resolve, reject) {
            if (!loaded && loader) {
                loader(item, function (newChildren) {
                    if (leaf) {
                        item.leafs = newChildren;
                        item.leafLoaded = true;
                    } else {
                        item.collections = newChildren;
                        item.collectionsLoaded = true;
                    }
                    resolve(newChildren);
                });
            } else {
                var res = (leaf ? leafs : collections) || [];
                resolve(res);
            }
        });
    };

    Loaders.listUsers = function listUsers(params, callback) {
        var parent = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2];

        var baseParams = { get_action: 'user_list_authorized_users', format: 'json' };
        baseParams = _extends({}, baseParams, params);
        var cb = callback;
        if (parent) {
            if (parent.range) {
                baseParams['range'] = parent.range;
            }
            cb = function (children) {
                callback(children.map(function (c) {
                    c._parent = parent;return c;
                }));
            };
        }
        PydioApi.getClient().request(baseParams, function (transport) {
            cb(transport.responseJSON);
            var cRange = transport.responseObject.headers.get('Content-Range');
            var aRange = transport.responseObject.headers.get('Accept-Range');
            if (cRange && aRange && parent) {
                var _aRange$split = aRange.split(' ');

                var type = _aRange$split[0];
                var interval = _aRange$split[1];

                var _cRange$split = cRange.split('/');

                var range = _cRange$split[0];
                var max = _cRange$split[1];

                var _range$split = range.split('-');

                var start = _range$split[0];
                var end = _range$split[1];

                parent.pagination = {
                    start: parseInt(start),
                    end: parseInt(end),
                    max: parseInt(max),
                    interval: parseInt(interval)
                };
            }
        });
    };

    Loaders.loadTeams = function loadTeams(entry, callback) {
        var wrapped = function wrapped(children) {
            children.map(function (child) {
                child.icon = 'mdi mdi-account-multiple';
                child.itemsLoader = Loaders.loadTeamUsers;
                child.actions = {
                    type: 'team',
                    create: '573',
                    remove: '574',
                    multiple: true
                };
                child._notSelectable = true;
            });
            callback(children);
        };
        Loaders.listUsers({ filter_value: 8 }, wrapped, entry);
    };

    Loaders.loadGroups = function loadGroups(entry, callback) {
        var wrapped = function wrapped(children) {
            children.map(function (child) {
                child.icon = 'mdi mdi-account-multiple';
                child.childrenLoader = entry.childrenLoader ? Loaders.loadGroups : null;
                child.itemsLoader = entry.itemsLoader ? Loaders.loadGroupUsers : null;
                if (entry.currentParams && entry.currentParams.alpha_pages) {
                    child.currentParams = _extends({}, entry.currentParams);
                }
            });
            callback(children);
        };
        var path = entry.id.replace('AJXP_GRP_', '');
        var params = { filter_value: 4, group_path: path };
        if (entry.currentParams && !entry.currentParams.alpha_pages) {
            params = _extends({}, params, entry.currentParams);
        }
        Loaders.listUsers(params, wrapped, entry);
    };

    Loaders.loadExternalUsers = function loadExternalUsers(entry, callback) {
        Loaders.listUsers({ filter_value: 2 }, callback, entry);
    };

    Loaders.loadGroupUsers = function loadGroupUsers(entry, callback) {
        var path = entry.id.replace('AJXP_GRP_', '');
        var params = { filter_value: 1, group_path: path };
        if (entry.currentParams) {
            params = _extends({}, params, entry.currentParams);
        }
        Loaders.listUsers(params, callback, entry);
    };

    Loaders.loadTeamUsers = function loadTeamUsers(entry, callback) {
        Loaders.listUsers({ filter_value: 3, group_path: entry.id }, callback, entry);
    };

    return Loaders;
})();

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