"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var bluebird_1 = __importDefault(require("bluebird"));
var Emitter_1 = __importDefault(require("./Emitter"));
var Organization = /** @class */ (function (_super) {
    __extends(Organization, _super);
    function Organization(api, auth) {
        var _this = _super.call(this) || this;
        _this.api = api;
        _this.auth = auth;
        _this.folders = [];
        _this.filteredFolders = [];
        _this.disabledFolders = [];
        _this.users = [];
        _this.filteredUsers = [];
        _this.folderPages = [];
        _this.folderFilter = {
            name: ''
        };
        _this.userFilter = {
            emails: '',
            screen_name: '',
            full_name: ''
        };
        _this.accessLevels = {
            RO: 'Read-only',
            RW: 'Read/write',
            PA: 'Page Administrator',
            FA: 'Folder Administrator',
            NO: 'Suspend'
        };
        _this.folderUsers = {};
        _this.folderInvites = {};
        // folder loop vars
        _this.folderCount = 0;
        return _this;
    }
    Organization.prototype.load = function () {
        var _this = this;
        // let q: any = this.$q.defer();
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.folders = [];
            _this.disabledFolders = [];
            _this.api
                .getOrganizationDomains({
                organizationId: _this.auth.user.organization_id
            })
                .then(function (results) {
                results.data.results.forEach(function (folder) {
                    // if (
                    //     !folder.current_user_domain_access ||
                    //     folder.current_user_domain_access.access_level !== "AD"
                    // ) {
                    //     return;
                    // }
                    var active = false;
                    ['active_admin', 'active_opa', 'active_row', 'active_rw'].forEach(function (access) {
                        if (folder.summary_domain_access[access] > 0) {
                            active = true;
                        }
                    });
                    folder._active = active;
                    _this.folders.push(folder);
                });
                // return (this.folders = results.data.results);
                _this.queryFolders();
                resolve(true);
            });
        });
        return p;
    };
    Organization.prototype.getUserFolderAcess = function (userId, folderId) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var data = {
                user: undefined,
                pages: []
            };
            var error;
            _this.api
                .domainUsers({ domainId: folderId })
                .then(function (result) {
                result.data.results.forEach(function (user) {
                    if (user.user.id !== userId) {
                        return;
                    }
                    data.user = user;
                    data.user.is_rw = ['RW', 'PA', 'FA'].indexOf(user.access_level) > -1 || user.is_administrator;
                });
                if (!data.user) {
                    data.user = 'NO';
                }
                return _this.api.getDomainPageAccess({ domainId: folderId });
            })
                .then(function (result) {
                var domains = result.data.user_domain_access;
                var pages = result.data.pages;
                var access = result.data.user_page_access;
                for (var p_1 = 0; p_1 < pages.length; p_1++) {
                    var page = pages[p_1];
                    page.access = {
                        access: 'no',
                        page_id: page.id,
                        user_id: userId
                    };
                    for (var a = 0; a < access.length; a++) {
                        var rights = access[a];
                        if (rights.user_id === userId && rights.page_id === page.id) {
                            page.access = rights;
                            break;
                        }
                    }
                    data.pages.push(page);
                }
            })
                .catch(function (err) {
                error = err;
            })
                .finally(function () {
                if (error) {
                    reject(error);
                    return;
                }
                resolve(data);
            });
        });
        return p;
    };
    Organization.prototype.updateFolderStatus = function (f) {
        var active = false;
        ['active_admin', 'active_opa', 'active_row', 'active_rw'].forEach(function (access) {
            if (f.summary_domain_access[access] > 0) {
                active = true;
            }
        });
        f._active = active;
        var inactive = false;
        ['inactive_admin', 'inactive_opa', 'inactive_row', 'inactive_rw'].forEach(function (access) {
            if (f.summary_domain_access[access] > 0) {
                inactive = true;
            }
        });
        f._inactive = inactive;
        return f;
    };
    Organization.prototype.queryFolders = function () {
        var _this = this;
        var folders = [];
        this.folders.forEach(function (f) {
            f = _this.updateFolderStatus(f);
            if (!_this.folderFilter.name) {
                folders.push(f);
                return;
            }
            if (f.name.toLowerCase().indexOf(_this.folderFilter.name.toLowerCase()) > -1) {
                folders.push(f);
            }
        });
        folders.sort(function (a, b) {
            if (a.name.toLowerCase() > b.name.toLowerCase()) {
                return 1;
            }
            if (a.name.toLowerCase() < b.name.toLowerCase()) {
                return -1;
            }
            return 0;
        });
        this.filteredFolders = folders;
    };
    Organization.prototype.queryUsers = function () {
        var _this = this;
        var users = [];
        this.users.forEach(function (f) {
            // if (!this.filter) {
            //     users.push(f);
            //     return;
            // }
            var add = true;
            if (_this.userFilter.emails) {
                var emails = _this.userFilter.emails.split(',');
                add = false;
                emails.forEach(function (email) {
                    if (!email.trim()) {
                        return;
                    }
                    if (f.email.indexOf(email.trim()) > -1) {
                        add = true;
                    }
                });
            }
            if (_this.userFilter.screen_name && f.screen_name.indexOf(_this.userFilter.screen_name) === -1) {
                add = false;
            }
            if (_this.userFilter.full_name && f.full_name.indexOf(_this.userFilter.full_name) === -1) {
                add = false;
            }
            if (add) {
                users.push(f);
            }
        });
        users.sort(function (a, b) {
            if (a.email > b.email) {
                return 1;
            }
            if (a.email < b.email) {
                return -1;
            }
            return 0;
        });
        this.filteredUsers = users;
    };
    Organization.prototype.inviteUsers = function (folder, users) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var emails = [];
            users.forEach(function (user) {
                emails.push({ email: user.email });
            });
            var requestData = {
                domainId: folder.id,
                data: {
                    emails: emails,
                    message: ''
                }
            };
            _this.api
                .inviteUsers(requestData)
                .then(function (response) {
                console.log(response);
                response.data.forEach(function (invitation) {
                    if (!_this.folderInvites[folder.id]) {
                        _this.folderInvites[folder.id] = {};
                    }
                    if (!_this.folderUsers[folder.id]) {
                        _this.folderUsers[folder.id] = {};
                    }
                    _this.folderInvites[folder.id][invitation.invited_user.id] = invitation;
                    _this.folderUsers[folder.id][invitation.invited_user.id] = {
                        access_level: 'RW',
                        is_pending: true,
                        is_active: false,
                        user: invitation.invited_user
                    };
                });
                // this.toastr.success("User has been invited to folder");
                resolve(response);
            })
                .catch(function (err) {
                // this.toastr.error(err.message);
                reject(err);
            });
        });
        return p;
    };
    Organization.prototype.removeInvites = function (folder, invitations) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var invites = [];
            invitations.forEach(function (invite) {
                invites.push({ id: invite.id });
            });
            var requestData = {
                domainId: folder.id,
                data: invites
            };
            // for (let i: number = 0; i < invitations.length; i++) {
            //     requestData.data.push({ id: invitations[i].id });
            // }
            _this.api.cancelInvitations(requestData).then(function (result) {
                // this.toastr.success("Invitation canceled");
                invitations.forEach(function (invite) {
                    _this.folderUsers[folder.id][invite.invited_user.id] = false;
                    _this.folderInvites[folder.id][invite.invited_user.id] = false;
                });
                resolve(result);
            }, function (err) {
                // this.toastr.error("Could not cancel invitaion");
                reject(err);
            });
        });
        return p;
    };
    Organization.prototype.setUserAccess = function (folder, users, level, active) {
        var _this = this;
        if (active === void 0) { active = false; }
        var p = new bluebird_1.default(function (resolve, reject) {
            var items = [];
            var isActive = level === 'NO' || active === false ? false : true;
            level = level === 'NO' ? undefined : level;
            users.forEach(function (user) {
                if (user.level) {
                    level = user.level;
                }
                items.push({
                    user_id: user.id,
                    access_level: level === 'NO' ? undefined : level,
                    is_active: isActive
                });
            });
            var requestData = {
                domainId: folder.id,
                data: items
            };
            _this.api
                .updateDomainAccess(requestData)
                .then(function (response) {
                // this.toastr.success("User access updated");
                users.forEach(function (user) {
                    if (!_this.folderUsers[folder.id]) {
                        _this.folderUsers[folder.id] = {};
                    }
                    if (level) {
                        _this.folderUsers[folder.id][user.id].access_level = level;
                    }
                    _this.folderUsers[folder.id][user.id].is_active = isActive;
                });
                resolve(response);
            })
                .catch(function (err) {
                // this.toastr.error(err.message);
                reject(err);
            });
        });
        return p;
    };
    Organization.prototype.removeUserAccess = function (folder, users) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var items = [];
            users.forEach(function (user) {
                items.push({
                    user_id: user.id
                });
            });
            var requestData = {
                domainId: folder.id,
                data: items
            };
            _this.api.removeUsersFromDomain(requestData).then(function (result) {
                // this.toastr.success("User removed");
                users.forEach(function (user) {
                    _this.folderUsers[folder.id][user.id] = false;
                });
                resolve(result);
            }, function (err) {
                // this.toastr.error("Could not remove user from folder");
                reject(err);
            });
        });
        return p;
    };
    Organization.prototype.updateUserPageAccess = function (folderId, pages, access, selected) {
        var _this = this;
        if (selected === void 0) { selected = false; }
        var p = new bluebird_1.default(function (resolve, reject) {
            var items = [];
            access = access === 'no' ? '' : access;
            pages.forEach(function (page) {
                if (selected && !page._selected) {
                    return;
                }
                items.push({
                    user_id: page.access.user_id,
                    page_id: page.access.page_id,
                    access: access
                });
            });
            var data = {
                domainId: folderId,
                data: items
            };
            if (!items.length) {
                reject({
                    message: 'No pages selected'
                });
                return;
            }
            _this.api
                .saveDomainPageAccess(data)
                .then(function (response) {
                // this.toastr.success("Access rights updated");
                pages.forEach(function (page) {
                    if (selected && !page._selected) {
                        return;
                    }
                    page.access.access = access || 'no';
                });
                resolve(true);
            })
                .catch(function (err) {
                reject(err);
            });
        });
        return p;
    };
    Organization.prototype.getTooltipStatus = function (user) {
        if (user.is_pending) {
            return 'Pending User';
        }
        if (user.is_active) {
            return 'Active User';
        }
        return 'Suspended User';
    };
    Organization.prototype.getStatusClass = function (user) {
        if (user.is_pending) {
            return 'pending';
        }
        if (user.is_active) {
            return 'active';
        }
        return 'inactive';
    };
    Organization.prototype.update = function (which, folder, data) {
        var _this = this;
        if (which === 'invite') {
            var users_1 = [];
            this.filteredUsers.forEach(function (user) {
                if (Object.keys(_this.folderUsers[folder.id][user.id]).length) {
                    return;
                }
                users_1.push(user);
            });
            if (users_1.length) {
                return this.inviteUsers(folder, users_1);
            }
        }
        if (which === 'cancel') {
            var invitations_1 = [];
            this.filteredUsers.forEach(function (user) {
                if (!_this.folderInvites[folder.id] || !_this.folderInvites[folder.id][user.id]) {
                    return;
                }
                invitations_1.push(_this.folderInvites[folder.id][user.id]);
            });
            if (invitations_1.length) {
                return this.removeInvites(folder, invitations_1);
            }
        }
        if (which === 'access') {
            var users_2 = [];
            this.filteredUsers.forEach(function (user) {
                if (!_this.folderUsers[folder.id] ||
                    !Object.keys(_this.folderUsers[folder.id][user.id]).length ||
                    _this.folderUsers[folder.id][user.id].is_pending
                // user.id === this.app.user.id
                ) {
                    return;
                }
                users_2.push(user);
            });
            if (users_2.length) {
                return this.setUserAccess(folder, users_2, data);
            }
        }
        if (which === 'remove') {
            var users = [];
            for (var u in this.folderUsers[folder.id]) {
                if (!Object.keys(this.folderUsers[folder.id][u]).length || this.folderUsers[folder.id][u].is_active) {
                    continue;
                }
                users.push({
                    id: this.folderUsers[folder.id][u].user.id
                });
            }
            if (users.length) {
                return this.removeUserAccess(folder, users);
            }
        }
        if (which === 'activate') {
            var users = [];
            for (var u in this.folderUsers[folder.id]) {
                if (!Object.keys(this.folderUsers[folder.id][u]).length ||
                    this.folderUsers[folder.id][u].is_active ||
                    this.folderUsers[folder.id][u].is_pending) {
                    continue;
                }
                users.push({
                    id: this.folderUsers[folder.id][u].user.id,
                    level: this.folderUsers[folder.id][u].access_level
                });
            }
            if (users.length) {
                return this.setUserAccess(folder, users, '', true);
            }
        }
        var p = new bluebird_1.default(function (resolve, reject) {
            setTimeout(function () {
                resolve();
            });
        });
        return p;
        // let q: any = this.$q.defer();
        // this.$timeout(() => {
        //   resolve();
        // }, 10);
        // return p;
    };
    Organization.prototype.getFolderUserAccess = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            // get folders
            _this.api
                .getOrganizationDomains({
                organizationId: _this.auth.user.organization_id
            })
                .then(function (results) {
                _this.folders = results.data.results;
                // get users
                return _this.api.getOrganizationUsers({
                    organizationId: _this.auth.user.organization_id
                });
            })
                .then(function (results) {
                _this.users = results.data.results;
                // get access for each domain. eeek
                return _this.getDomainUsersQ();
            })
                .then(function (results) {
                return true;
            })
                .catch(function (err) {
                console.log(err);
            })
                .finally(function () {
                _this.queryFolders();
                _this.queryUsers();
                resolve({ users: _this.filteredUsers, folders: _this.filteredFolders });
            });
        });
        return p;
    };
    Organization.prototype.getDomainUsersQ = function () {
        var _this = this;
        this.folderCount = 0;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.folderPromiseResolve = resolve;
            _this.folderPromiseReject = reject;
        });
        // this.folderQ = this.$q.defer();
        this.getDomainUsers();
        return p;
    };
    Organization.prototype.getDomainUsers = function () {
        var _this = this;
        var folder = this.folders[this.folderCount];
        if (!this.folderUsers[folder.id]) {
            this.folderUsers[folder.id] = {};
        }
        if (!this.folderInvites[folder.id]) {
            this.folderInvites[folder.id] = {};
        }
        this.api
            .domainUsers({ domainId: folder.id })
            .then(function (results) {
            results.data.results.forEach(function (permission) {
                // TODO: Stats
                permission._stats = {
                    pushes: Math.floor(Math.random() * 1500)
                };
                _this.folderUsers[folder.id][permission.user.id] = permission;
            });
            // get folder invitations
            return _this.api.domainInvitations({ domainId: folder.id });
        })
            .then(function (results) {
            results.data.results.forEach(function (invitation) {
                _this.folderInvites[folder.id][invitation.invited_user.id] = invitation;
            });
            return true;
        })
            .catch(function () {
            _this.folderUsers[folder.id] = false;
            _this.folderInvites[folder.id] = false;
        })
            .finally(function () {
            // assign missing users
            _this.users.forEach(function (user) {
                if (!_this.folderUsers[folder.id][user.id]) {
                    _this.folderUsers[folder.id][user.id] = {};
                }
            });
            _this.folderCount++;
            if (_this.folderCount >= _this.folders.length) {
                // stop!
                _this.folderPromiseResolve(true);
                return;
            }
            _this.getDomainUsers();
        });
    };
    return Organization;
}(Emitter_1.default));
exports.default = Organization;
//# sourceMappingURL=Organization.js.map