"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var moment_timezone_1 = __importDefault(require("moment-timezone"));
var bluebird_1 = __importDefault(require("bluebird"));
var deepmerge_1 = __importDefault(require("deepmerge"));
var api, auth;
var UsageWrap = /** @class */ (function () {
    function UsageWrap(ippApi, ippAuth) {
        api = ippApi;
        auth = ippAuth;
    }
    return UsageWrap;
}());
exports.UsageWrap = UsageWrap;
var Usage = /** @class */ (function () {
    function Usage(api, auth) {
        this.api = api;
        this.auth = auth;
        // org users
        // org folders
        this.folders = [];
        this.filteredFolders = [];
        this.folderFilter = {
            name: ''
        };
        this.pages = [];
        this.filteredPages = [];
        this.pageFilter = {
            name: ''
        };
        this.users = [];
        this.filteredUsers = [];
        this.userFilter = {
            emails: '',
            screen_name: '',
            full_name: ''
        };
        this.stats = {};
        this.orgStats = {};
        this.indicator = 'usage';
        this.type = 'PUSH';
        this.output = 'percentage';
        this.threshold = {
            percentage: {
                from: 25,
                to: 75
            },
            count: {
                from: 100,
                to: 1000
            },
            usage: {
                from: 1,
                to: 3
            }
        };
        this.sortBy = {
            folders: {
                users: 'usage',
                folders: 'usage'
            },
            pages: {
                users: 'usage',
                folders: 'usage'
            }
        };
        this.date = {
            from: moment_timezone_1.default()
                .subtract(30, 'days')
                .format('YYYYMMDD'),
            to: moment_timezone_1.default().format('YYYYMMDD')
        };
        this.datePicker = {
            date: {
                startDate: moment_timezone_1.default().subtract(30, 'days'),
                endDate: moment_timezone_1.default()
            },
            options: {
                locale: {
                    cancelLabel: 'Cancel'
                },
                drops: 'down',
                opens: 'left',
                eventHandlers: {
                    'apply.daterangepicker': undefined
                },
                ranges: {
                    'Last 30 Days': [moment_timezone_1.default().subtract(30, 'days'), moment_timezone_1.default()],
                    'Last 7 Days': [moment_timezone_1.default().subtract(7, 'days'), moment_timezone_1.default()],
                    'Previous day': [moment_timezone_1.default(), moment_timezone_1.default().add(1, 'days')]
                }
            }
        };
        this.statTotals = {
            PULL: {
                count: 0,
                usage: 0
            },
            PUSH: {
                count: 0,
                usage: 0
            }
        };
        this.statTotalsByFolder = {};
        this.folderId = 0;
        this.statDefault = {
            PULL: {
                count: 0,
                usage: 0
            },
            PUSH: {
                count: 0,
                usage: 0
            }
        };
    }
    Usage.prototype.load = function (folderId) {
        var _this = this;
        this.folderId = folderId === undefined ? 0 : folderId;
        this.folders = [];
        this.pages = [];
        this.orgStats = {};
        this.stats = {};
        this.statTotals = deepmerge_1.default({}, this.statDefault);
        this.statTotalsByFolder = {};
        // this.q = this.$q.defer();
        var p = new bluebird_1.default(function (resolve, reject) {
            _this.emptyAsync()
                .then(function () {
                if (folderId) {
                    return _this.api.getDomainPages(folderId);
                }
                else {
                    return _this.api.getOrganizationDomains({
                        organizationId: _this.auth.user.organization_id
                    });
                }
            })
                .then(function (response) {
                if (folderId) {
                    _this.pages = response.data.pages || [];
                    return _this.api.getDomainPageAccess({
                        domainId: folderId
                    });
                }
                else {
                    _this.folders = response.data.results || [];
                    return _this.api.getOrganizationUsers({
                        organizationId: _this.auth.user.organization_id
                    });
                }
            })
                .then(function (response) {
                if (folderId) {
                    _this.users = [];
                    var users = response.data.user_domain_access;
                    users.forEach(function (user) {
                        _this.users.push(user.user);
                    });
                    return _this.api.getDomainUsage({
                        domainId: folderId,
                        fromDate: _this.date.from,
                        toDate: _this.date.to
                    });
                }
                else {
                    _this.users = response.data.results || [];
                    return _this.api.getOrganizationUsage({ fromDate: _this.date.from, toDate: _this.date.to });
                }
            })
                .then(function (response) {
                if (folderId) {
                    response.data.results.forEach(function (result) {
                        if (!result.user_id) {
                            return;
                        }
                        // check if user exits
                        var count = false;
                        _this.users.forEach(function (user) {
                            if (user.id !== result.user_id) {
                                return;
                            }
                            count = true;
                        });
                        if (!count) {
                            return;
                        }
                        // overall
                        _this.statTotals[result.request_method].count += result.total_requests;
                        _this.statTotals[result.request_method].usage += result.total_requests_size;
                        // by folder
                        if (!_this.statTotalsByFolder[result.page_id]) {
                            _this.statTotalsByFolder[result.page_id] = deepmerge_1.default({}, _this.statDefault);
                        }
                        _this.statTotalsByFolder[result.page_id][result.request_method].count += result.total_requests;
                        _this.statTotalsByFolder[result.page_id][result.request_method].usage += result.total_requests_size;
                        if (!_this.stats[result.user_id]) {
                            _this.stats[result.user_id] = {};
                        }
                        if (!_this.stats[result.user_id][result.page_id]) {
                            _this.stats[result.user_id][result.page_id] = deepmerge_1.default({}, _this.statDefault);
                        }
                        _this.stats[result.user_id][result.page_id][result.request_method] = {
                            count: result.total_requests,
                            usage: result.total_requests_size
                        };
                    });
                }
                else {
                    response.data.results.forEach(function (result) {
                        // overall
                        _this.statTotals[result.request_method].count += result.total_requests;
                        _this.statTotals[result.request_method].usage += result.total_requests_size;
                        // by folder
                        if (!_this.statTotalsByFolder[result.domain_id]) {
                            _this.statTotalsByFolder[result.domain_id] = deepmerge_1.default({}, _this.statDefault);
                        }
                        _this.statTotalsByFolder[result.domain_id][result.request_method].count += result.total_requests;
                        _this.statTotalsByFolder[result.domain_id][result.request_method].usage += result.total_requests_size;
                        if (!result.user_id) {
                            return;
                        }
                        if (!_this.orgStats[result.user_id]) {
                            _this.orgStats[result.user_id] = {};
                        }
                        if (!_this.orgStats[result.user_id][result.domain_id]) {
                            _this.orgStats[result.user_id][result.domain_id] = deepmerge_1.default({}, _this.statDefault);
                        }
                        _this.orgStats[result.user_id][result.domain_id][result.request_method] = {
                            count: result.total_requests,
                            usage: result.total_requests_size
                        };
                    });
                }
                _this.users.forEach(function (user) {
                    user.stats = deepmerge_1.default({}, _this.statDefault);
                    var pagesFolders = folderId ? _this.pages : _this.folders;
                    var statsData = folderId ? _this.stats : _this.orgStats;
                    pagesFolders.forEach(function (n) {
                        if (!statsData[user.id] || !statsData[user.id][n.id]) {
                            if (!statsData[user.id]) {
                                statsData[user.id] = {};
                            }
                            statsData[user.id][n.id] = deepmerge_1.default({}, _this.statDefault);
                            return;
                        }
                        ['PULL', 'PUSH'].forEach(function (method) {
                            user.stats[method].count += statsData[user.id][n.id][method]
                                ? statsData[user.id][n.id][method].count
                                : 0;
                            user.stats[method].usage += statsData[user.id][n.id][method]
                                ? statsData[user.id][n.id][method].usage
                                : 0;
                        });
                    });
                });
                console.log('users', _this.users);
            })
                .catch(reject)
                .finally(function () {
                if (folderId) {
                    _this.queryPages();
                }
                else {
                    _this.queryFolders();
                }
                console.log('finally');
                console.log(_this.statTotals);
                console.log(_this.statTotalsByFolder);
                _this.queryUsers();
                resolve({
                    users: _this.filteredUsers,
                    pages: _this.filteredPages,
                    folders: _this.filteredFolders,
                    stats: _this.stats,
                    statTotals: _this.statTotals,
                    statTotalsByFolder: _this.statTotalsByFolder,
                    orgStats: _this.orgStats
                });
            });
        });
        return p;
        // return this.q.promise;
    };
    Usage.prototype.setSortBy = function (which, type, value) {
        this.sortBy[which][type] = value;
        this.queryUsers();
        this.queryFolders();
        this.queryPages();
    };
    Usage.prototype.queryFolders = function () {
        var _this = this;
        var folders = [];
        var folderNames = this.folderFilter.name.split(',');
        this.folders.forEach(function (f) {
            // f = this.updateFolderStatus(f);
            if (!_this.folderFilter.name) {
                folders.push(f);
                return;
            }
            folderNames.forEach(function (name) {
                name = name.trim();
                if (!name) {
                    return;
                }
                if (f.name.toLowerCase().indexOf(name.toLowerCase()) > -1 && folders.indexOf(f) < 0) {
                    folders.push(f);
                }
            });
        });
        folders.sort(function (a, b) {
            // if (this.folderId) {
            if ((_this.folderId && _this.sortBy.pages.folders === 'usage') ||
                (!_this.folderId && _this.sortBy.folders.folders === 'usage')) {
                var aStat = _this.statTotalsByFolder[a.id]
                    ? _this.statTotalsByFolder[a.id][_this.type][_this.indicator]
                    : 0;
                var bStat = _this.statTotalsByFolder[b.id]
                    ? _this.statTotalsByFolder[b.id][_this.type][_this.indicator]
                    : 0;
                if (aStat < bStat) {
                    return 1;
                }
                if (aStat > bStat) {
                    return -1;
                }
                return 0;
            }
            // }
            if (a.name.toLowerCase() > b.name.toLowerCase()) {
                return 1;
            }
            if (a.name.toLowerCase() < b.name.toLowerCase()) {
                return -1;
            }
            return 0;
        });
        this.filteredFolders = folders;
    };
    Usage.prototype.queryPages = function () {
        var _this = this;
        var pages = [];
        var pageNames = this.pageFilter.name.split(',');
        this.pages.forEach(function (f) {
            // f = this.updateFolderStatus(f);
            if (!_this.pageFilter.name) {
                pages.push(f);
                return;
            }
            pageNames.forEach(function (name) {
                name = name.trim();
                if (!name) {
                    return;
                }
                if (f.name.toLowerCase().indexOf(name.toLowerCase()) > -1 && pages.indexOf(f) < 0) {
                    pages.push(f);
                }
            });
        });
        pages.sort(function (a, b) {
            if (_this.folderId) {
                if (_this.sortBy.pages.folders === 'usage') {
                    var aStat = _this.statTotalsByFolder[a.id]
                        ? _this.statTotalsByFolder[a.id][_this.type][_this.indicator]
                        : 0;
                    var bStat = _this.statTotalsByFolder[b.id]
                        ? _this.statTotalsByFolder[b.id][_this.type][_this.indicator]
                        : 0;
                    if (aStat < bStat) {
                        return 1;
                    }
                    if (aStat > bStat) {
                        return -1;
                    }
                    return 0;
                }
            }
            if (a.name.toLowerCase() > b.name.toLowerCase()) {
                return 1;
            }
            if (a.name.toLowerCase() < b.name.toLowerCase()) {
                return -1;
            }
            return 0;
        });
        this.filteredPages = pages;
    };
    Usage.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 (_this.folderId) {
                if (_this.sortBy.pages.users === 'usage') {
                    if (a.stats[_this.type][_this.indicator] < b.stats[_this.type][_this.indicator]) {
                        return 1;
                    }
                    if (a.stats[_this.type][_this.indicator] > b.stats[_this.type][_this.indicator]) {
                        return -1;
                    }
                    return 0;
                }
            }
            else {
                if (_this.sortBy.folders.users === 'usage') {
                    if (a.stats[_this.type][_this.indicator] < b.stats[_this.type][_this.indicator]) {
                        return 1;
                    }
                    if (a.stats[_this.type][_this.indicator] > b.stats[_this.type][_this.indicator]) {
                        return -1;
                    }
                    return 0;
                }
            }
            if (a.email.toLowerCase() > b.email.toLowerCase()) {
                return 1;
            }
            if (a.email.toLowerCase() < b.email.toLowerCase()) {
                return -1;
            }
            return 0;
        });
        this.filteredUsers = users;
    };
    Usage.prototype.convertNumber = function (indicator, value) {
        if (!value) {
            return '0';
        }
        if (indicator === 'usage') {
            value = parseFloat((value / 1024 / 1024).toFixed(1)).toLocaleString();
            if (!parseFloat(value)) {
                value = '0.1';
            }
        }
        value = value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        return value || '0';
    };
    Usage.prototype.pageFolderPercentage = function (type, indicator, value) {
        if (!value) {
            return '0';
        }
        return ((value / this.statTotals[type][indicator]) * 100).toFixed(1);
    };
    Usage.prototype.cellClass = function (stat, folderId) {
        if (!stat) {
            return 'NA';
        }
        var from = this.output === 'percentage' ? this.threshold.percentage.from : this.threshold[this.indicator].from;
        var to = this.output === 'percentage' ? this.threshold.percentage.to : this.threshold[this.indicator].to;
        if (this.indicator === 'usage' && this.output !== 'percentage') {
            stat = stat / 1024 / 1024;
        }
        else if (this.output === 'percentage' && folderId) {
            stat = (stat / this.statTotalsByFolder[folderId][this.type][this.indicator]) * 100;
        }
        if (stat < from) {
            return '';
        }
        if (stat >= from && stat <= to) {
            return 'RW';
        }
        if (stat > to) {
            return 'NO';
        }
        return '';
    };
    Usage.prototype.cellValue = function (pushes, folderId) {
        if (!pushes) {
            return '';
        }
        var value = pushes[this.indicator];
        if (!value) {
            return '';
        }
        if (this.output === 'percentage' && folderId) {
            if (!this.statTotalsByFolder[folderId]) {
                value = '#';
            }
            else {
                value = ((value / this.statTotalsByFolder[folderId][this.type][this.indicator]) * 100).toFixed(1);
            }
        }
        else if (this.indicator === 'usage') {
            value = parseFloat((value / 1024 / 1024).toFixed(1));
            if (!parseFloat(value)) {
                value = 0.1;
            }
        }
        return value;
    };
    Usage.prototype.emptyAsync = function () {
        var p = new bluebird_1.default(function (resolve) {
            resolve();
        });
        return p;
    };
    Usage.$inject = ['$timeout', '$interval', '$q', 'ippApiService', 'ippAuthService'];
    return Usage;
}());
exports.default = Usage;
//# sourceMappingURL=Usage.js.map