"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 Emitter_1 = __importDefault(require("./Emitter"));
var bluebird_1 = __importDefault(require("bluebird"));
var api, auth;
var FolderWrap = /** @class */ (function () {
    function FolderWrap(
    // q: IQService,
    // timeout: ITimeoutService,
    // interval: IIntervalService,
    ippApi, ippAuth) {
        api = ippApi;
        auth = ippAuth;
    }
    return FolderWrap;
}());
exports.FolderWrap = FolderWrap;
var IFolderDataUserAccessLevel;
(function (IFolderDataUserAccessLevel) {
    IFolderDataUserAccessLevel["FA"] = "FA";
    IFolderDataUserAccessLevel["PA"] = "PA";
    IFolderDataUserAccessLevel["RW"] = "RW";
    IFolderDataUserAccessLevel["RO"] = "RO";
})(IFolderDataUserAccessLevel = exports.IFolderDataUserAccessLevel || (exports.IFolderDataUserAccessLevel = {}));
var Folder = /** @class */ (function (_super) {
    __extends(Folder, _super);
    function Folder(id) {
        var _this = _super.call(this) || this;
        _this.id = 0;
        _this.hasAccess = false;
        _this.history = [];
        _this.orgUsers = [];
        _this.users = [];
        _this.currentUsers = [];
        _this.suspendedUsers = [];
        _this.pendingUsers = [];
        _this.invitedUsers = [];
        _this.pendingAccess = [];
        if (id)
            _this.id = id;
        return _this;
    }
    Object.defineProperty(Folder.prototype, "PAGE_ACCESS_BASIC", {
        get: function () {
            return 1;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Folder.prototype, "PAGE_ACCESS_ENTERPRISE", {
        get: function () {
            return 0;
        },
        enumerable: true,
        configurable: true
    });
    Folder.prototype.load = function (id, pageId) {
        var _this = this;
        this.id = parseInt("" + id);
        this.hasAccess = false;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.getData()
                .then(function () {
                return _this.getHistory();
            })
                .then(function () {
                return _this.getUserAccess(pageId);
            })
                .then(function () {
                return _this.getOrgUsers();
            })
                .then(function () {
                return _this.getDomainInvitations();
            })
                .then(function () {
                return _this.getDomainUsers();
            })
                .then(function () {
                resolve({
                    data: _this.data,
                    history: _this.history,
                    hasAccess: _this.hasAccess,
                    orgUsers: _this.orgUsers,
                    currentUsers: _this.currentUsers,
                    suspendedUsers: _this.suspendedUsers,
                    pendingUsers: _this.pendingUsers,
                    pendingAccess: _this.pendingAccess,
                    invitedUsers: _this.invitedUsers,
                    users: _this.users
                });
            })
                .catch(reject);
        });
        return p;
    };
    Folder.prototype.getPageAccess = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.getData()
                .then(function () {
                api.getDomainPageAccess({ domainId: _this.id }).then(function (result) {
                    var userPageAccess = result.data.user_page_access;
                    var users = result.data.user_domain_access;
                    var domainPages = result.data.pages;
                    var access = {};
                    userPageAccess.forEach(function (level) {
                        if (!access[level.page_id]) {
                            access[level.page_id] = {};
                        }
                        access[level.page_id][level.user_id] = level.access;
                    });
                    var sheets = [], pdfs = [], liveusages = [], singledomains = [], domainpages = [], alerts = [], others = [];
                    domainPages.forEach(function (page) {
                        if (!access[page.id]) {
                            access[page.id] = {};
                        }
                        users.forEach(function (user) {
                            if (!access[page.id][user.user.id]) {
                                access[page.id][user.user.id] = 'no';
                            }
                        });
                        if (page.special_page_type === 0) {
                            sheets.push(page);
                        }
                        else if (page.special_page_type === 6) {
                            pdfs.push(page);
                        }
                        else if (page.special_page_type === 5) {
                            alerts.push(page);
                        }
                        else if (page.special_page_type === 4) {
                            domainpages.push(page);
                        }
                        else if (page.special_page_type === 2) {
                            singledomains.push(page);
                        }
                        else if (page.special_page_type === 7) {
                            liveusages.push(page);
                        }
                        else {
                            others.push(page);
                        }
                    });
                    var sort = function (a, b) {
                        if (a.user) {
                            if (a.user.email > b.user.email)
                                return 1;
                            if (a.user.email < b.user.email)
                                return -1;
                            return 0;
                        }
                        if (a.name > b.name)
                            return 1;
                        if (a.name < b.name)
                            return -1;
                        return 0;
                    };
                    var mapUser = function (user) {
                        user._administrator = ['FA'].indexOf(user.access_level) > -1 || user.is_administrator;
                        return user;
                    };
                    var pages = [].concat(pdfs.sort(sort), sheets.sort(sort), singledomains.sort(sort), domainpages.sort(sort), liveusages.sort(sort), alerts.sort(sort), others.sort(sort));
                    resolve({
                        data: _this.data,
                        users: users.map(mapUser).sort(sort),
                        pages: pages,
                        access: access
                    });
                }, reject);
            })
                .catch(reject);
        });
        return p;
    };
    Folder.prototype.getData = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            api
                .getDomain(_this.id)
                .then(function (res) {
                _this.data = res.data;
                _this.hasAccess =
                    _this.data.current_user_domain_access &&
                        (_this.data.current_user_domain_access.access_level === IFolderDataUserAccessLevel.PA ||
                            _this.data.current_user_domain_access.access_level === IFolderDataUserAccessLevel.FA ||
                            _this.data.current_user_domain_access.is_administrator);
                resolve(_this.data);
            })
                .catch(reject);
        });
        return p;
    };
    Folder.prototype.getHistory = function (limit) {
        var _this = this;
        if (limit === void 0) { limit = 15; }
        var p = new bluebird_1.default(function (resolve, reject) {
            api
                .domainAccessLog({ domainId: _this.id, limit: limit })
                .then(function (res) {
                _this.history = res.data.results;
                resolve(_this.history);
            })
                .catch(resolve);
        });
        return p;
    };
    Folder.prototype.getUserAccess = function (pageId) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            api.getDomainPageAccess({ domainId: _this.id }).then(function (result) {
                var users = result.data.user_domain_access;
                var pages = result.data.user_page_access;
                var ownPage;
                users.forEach(function (user) {
                    // user.text = user.user.email;
                    user.own_page = false;
                    user.access = {
                        user_id: user.user.id,
                        page_id: pageId || 0,
                        access: ''
                    };
                    if (user.user.id === auth.user.id) {
                        result.data.pages.forEach(function (page) {
                            if (page.id !== pageId)
                                return;
                            user.own_page = page.own_page;
                        });
                    }
                    pages.forEach(function (page) {
                        if (page.page_id !== pageId || page.user_id !== user.user.id) {
                            return;
                        }
                        user.access = page;
                    });
                });
                _this.users = users;
                resolve(users);
            }).catch(reject);
        });
        return p;
    };
    Folder.prototype.getOrgUsers = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            if (!auth.user.organization) {
                resolve();
                return;
            }
            api
                .getOrganizationLinkedUsers({ organizationId: auth.user.organization_id })
                .then(function (res) {
                var users = [];
                var emails = [];
                _this.users.forEach(function (user) {
                    emails.push(user.user.email);
                });
                res.data.results.forEach(function (user) {
                    // if (emails.indexOf(user.email) > -1) {
                    //   return;
                    // }
                    user.text = user.first_name + " " + user.last_name + " (" + user.email + ")";
                    users.push(user);
                });
                _this.orgUsers = users;
                resolve(_this.orgUsers);
            })
                .catch(resolve);
        });
        return p;
    };
    Folder.prototype.getDomainInvitations = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            // Get domain invitations
            api.domainInvitations({ domainId: _this.id }).then(function (result) {
                _this.invitedUsers = result.data.results;
                resolve(_this.invitedUsers);
            }, reject); // @todo: deal with error
        });
        return p;
    };
    Folder.prototype.getDomainUsers = function () {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            api.domainUsers({ domainId: _this.id }).then(function (result) {
                _this.currentUsers = [];
                _this.suspendedUsers = [];
                result.data.results.forEach(function (user) {
                    if (!_this.pendingAccess[user.user.id] || !_this.pendingAccess[user.user.id]._dirty) {
                        _this.pendingAccess[user.user.id] = user;
                    }
                    if (user.is_active) {
                        _this.currentUsers.push(user);
                    }
                    else if (!user.is_pending) {
                        _this.suspendedUsers.push(user);
                    }
                    else if (user.is_pending) {
                        // find invitation
                        _this.invitedUsers.forEach(function (invitation) {
                            if (invitation.email !== user.user.email)
                                return;
                            user.invitation = invitation;
                        });
                        _this.pendingUsers.push(user);
                    }
                });
                resolve({
                    currentUsers: _this.currentUsers,
                    suspendedUsers: _this.suspendedUsers,
                });
            }, reject); // @todo: deal with error
        });
        return p;
    };
    Folder.prototype.updateUserDomainAccess = function (users, level, active) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var requestData = {
                domainId: _this.id,
                data: []
            };
            users.forEach(function (user) {
                requestData.data.push({
                    user_id: user.user.invited_user ? user.user.invited_user.id : user.user.id,
                    access_level: typeof level !== 'string' ? user.access_level : level,
                    is_active: typeof active !== 'boolean' ? user.is_active : active
                });
            });
            api.updateDomainAccess(requestData).then(function () {
                users.forEach(function (user) {
                    if (level)
                        user.access_level = level;
                    if (typeof active === 'boolean')
                        user.is_active = active;
                });
                resolve(users);
            }, reject);
        });
        return p;
    };
    Folder.prototype.removeUserDomainAccess = function (users) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var ids = [];
            users.forEach(function (user) {
                // if (!user.invitation) return;
                ids.push({ user_id: user.user.id });
            });
            var requestData = {
                domainId: _this.id,
                data: ids
            };
            api.removeUsersFromDomain(requestData).then(function () {
                resolve(users);
            }, reject);
        });
        return p;
    };
    Folder.prototype.addUserDomainAccess = function (users, isEnterprise) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var emails = [];
            users.forEach(function (friend) {
                emails.push({ email: friend.email });
            });
            var requestData = {
                domainId: _this.id,
                data: {
                    emails: emails
                }
            };
            api.inviteUsers(requestData).then(function (results) {
                resolve(results.data);
            }, reject);
        });
        return p;
    };
    Folder.prototype.cancelUserDomainAccess = function (users) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            var ids = [];
            users.forEach(function (user) {
                if (user.invitation) {
                    ids.push({ id: user.invitation.id });
                }
                else if (user.user && user.user.invited_user) {
                    ids.push({ id: user.user.id });
                }
            });
            var requestData = {
                domainId: _this.id,
                data: ids
            };
            api.cancelInvitations(requestData).then(function (results) {
                resolve(results.data);
            }, reject);
        });
        return p;
    };
    return Folder;
}(Emitter_1.default));
exports.Folder = Folder;
//# sourceMappingURL=Folder.js.map