"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 __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var uuid = __importStar(require("uuid"));
var Emitter_1 = __importDefault(require("./Emitter"));
var bluebird_1 = __importDefault(require("bluebird"));
var request = __importStar(require("xhr"));
var Helpers_1 = __importDefault(require("./Helpers"));
var Utils_1 = __importDefault(require("./Utils"));
var ApiError = /** @class */ (function (_super) {
    __extends(ApiError, _super);
    function ApiError(params) {
        var _this = _super.call(this, params.message) || this;
        _this.method = '';
        _this.code = 0;
        _this.statusCode = 0;
        _this.httpCode = 0;
        _this.error = {};
        _this.httpText = '';
        Object.keys(params).forEach(function (param) {
            _this[param] = params[param];
        });
        return _this;
    }
    return ApiError;
}(Error));
exports.ApiError = ApiError;
var Request = /** @class */ (function () {
    function Request(method, url) {
        this._headers = {};
        this._cache = false;
        this._overrideLock = false;
        this._json = true;
        this._reponse_type = '';
        this._method = method;
        this._url = url;
        this._headers = {
            // "Strict-Transport-Security": "max-age=15768000;includeSubDomains",
            'Content-Type': 'application/json',
            'x-requested-with': 'XMLHttpRequest',
            'x-ipp-device-uuid': Request.config.uuid || Request.uuid,
            'x-ipp-client': Request.config.api_key,
            'x-ipp-client-version': Request.config.client_version || '1.0',
        };
        if (Request.config.hsts) {
            this._headers['Strict-Transport-Security'] = 'max-age=15768000;includeSubDomains';
        }
    }
    Request.get = function (url) {
        return new Request('GET', url);
    };
    Request.post = function (url) {
        return new Request('POST', url);
    };
    Request.put = function (url) {
        return new Request('PUT', url);
    };
    Request.del = function (url) {
        return new Request('DELETE', url);
    };
    Object.defineProperty(Request.prototype, "METHOD", {
        // @todo Bleh...
        get: function () {
            return this._method;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "URL", {
        get: function () {
            return this._url;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "HEADERS", {
        get: function () {
            return this._headers;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "DATA", {
        get: function () {
            return this._data;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "PARAMS", {
        get: function () {
            return this._params;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "CACHE", {
        get: function () {
            return this._cache;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "OVERRIDE_LOCK", {
        get: function () {
            return this._overrideLock;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "JSON", {
        get: function () {
            return this._json;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Request.prototype, "RESPONSE_TYPE", {
        get: function () {
            return this._reponse_type;
        },
        enumerable: true,
        configurable: true
    });
    Request.prototype.method = function (method) {
        this._method = method;
        return this;
    };
    Request.prototype.url = function (url) {
        this._url = url;
        return this;
    };
    Request.prototype.headers = function (headers, overwrite) {
        if (overwrite === void 0) { overwrite = false; }
        this._headers = overwrite ? headers : Object.assign({}, this._headers, headers);
        return this;
    };
    Request.prototype.data = function (data, serialize) {
        if (serialize === void 0) { serialize = false; }
        if (serialize) {
            this._data = Object.keys(data)
                .map(function (k) {
                return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
            })
                .join('&');
        }
        else {
            this._data = data;
        }
        return this;
    };
    Request.prototype.params = function (params, overwrite) {
        if (overwrite === void 0) { overwrite = false; }
        this._params = overwrite ? params : Object.assign({}, this._params, params);
        return this;
    };
    Request.prototype.cache = function (cache) {
        // Allow cache only for GET requests
        if (cache && this._method === 'GET') {
            this._cache = cache;
        }
        return this;
    };
    Request.prototype.overrideLock = function (override) {
        if (override === void 0) { override = true; }
        this._overrideLock = override;
        return this;
    };
    Request.prototype.json = function (json) {
        if (json === void 0) { json = true; }
        this._json = json;
        return this;
    };
    Request.prototype.responseType = function (str) {
        if (str === void 0) { str = ''; }
        this._reponse_type = str;
        return this;
    };
    Request.xipp = {
        uuid: '',
        client: '',
        clientVersion: '',
        hsts: true,
    };
    return Request;
}());
var Api = /** @class */ (function (_super) {
    __extends(Api, _super);
    function Api(config, storage) {
        var _this = _super.call(this) || this;
        _this.config = config;
        _this.storage = storage;
        _this.tokens = {
            access_token: '',
            refresh_token: '',
        };
        _this.lockedTimeCheck = 10000;
        // private _endPoint: string;
        _this._locked = false;
        _this.dummyRequest = function (data) {
            console.log('Api is locked down, preventing call ' + data.url);
            var p = new bluebird_1.default(function (resolve, reject) {
                reject(new ApiError({
                    data: data,
                    code: 666,
                    statusCode: 666,
                    message: 'Api is locked',
                }));
            });
            return p;
        };
        _this.handleSuccess = function (response) {
            return {
                success: true,
                data: response.body,
                httpCode: parseInt(response.statusCode, 10),
                httpText: response.statusMessage,
            };
        };
        _this.request = request.default;
        // this.END_POINT = `${this.config.api_url}`;
        var _uuid = storage.persistent.get('ipp_uuid', '', true);
        if (!_uuid) {
            _uuid = uuid.v4();
            storage.persistent.save('ipp_uuid', _uuid, 365, true);
        }
        Request.config = config;
        Request.uuid = _uuid;
        _this.helpers = new Helpers_1.default();
        _this.utils = new Utils_1.default();
        return _this;
    }
    Object.defineProperty(Api.prototype, "EVENT_REQ", {
        get: function () {
            return 'req';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Api.prototype, "EVENT_401", {
        get: function () {
            return '401';
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Api.prototype, "END_POINT", {
        get: function () {
            return this.config.api_url;
        },
        enumerable: true,
        configurable: true
    });
    Api.prototype.block = function () {
        this._locked = true;
        this._lockedTime = new Date();
    };
    Api.prototype.unblock = function () {
        this._locked = false;
    };
    Api.prototype.getSelfInfo = function () {
        return this.send(Request.get(this.END_POINT + '/users/self/')
            .cache(false)
            .overrideLock());
    };
    Api.prototype.refreshAccessTokens = function (refreshToken) {
        return this.send(Request.post(this.END_POINT + '/oauth/token/')
            .data({
            grant_type: 'refresh_token',
            client_id: this.config.api_key,
            client_secret: this.config.api_secret,
            refresh_token: refreshToken,
        }, true)
            .headers({
            'Content-Type': 'application/x-www-form-urlencoded',
        })
            .json(false)
            .overrideLock());
    };
    Api.prototype.userLogin = function (data) {
        return this.send(Request.post(this.END_POINT + '/oauth/token/')
            .data({
            grant_type: 'password',
            client_id: this.config.api_key,
            client_secret: this.config.api_secret,
            username: data.email,
            password: data.password,
        }, true)
            .headers({
            'Content-Type': 'application/x-www-form-urlencoded',
        })
            .json(false));
    };
    Api.prototype.userLoginByCode = function (data) {
        return this.send(Request.post(this.END_POINT + '/oauth/token/')
            .params(Object.assign({}, {
            grant_type: 'authorization_code',
            client_id: this.config.api_key,
            client_secret: this.config.api_secret,
        }, data))
            .headers({
            'Content-Type': 'application/x-www-form-urlencoded',
        }));
    };
    Api.prototype.userLogout = function (data) {
        if (data === void 0) { data = {}; }
        return this.send(Request.post(this.END_POINT + '/oauth/logout/').params({ all: data.all || '' }));
    };
    Api.prototype.getIntegrationChannels = function () {
        return this.send(Request.get(this.END_POINT + '/organizations/self/integration_channels/'));
    };
    Api.prototype.getIntegrationChannel = function (data) {
        return this.send(Request.get(this.END_POINT + '/integration_channels/' + data.id + '/'));
    };
    Api.prototype.createIntegrationChannel = function (data) {
        return this.send(Request.post(this.END_POINT + '/organizations/self/integration_channels/').data(data.data));
    };
    Api.prototype.saveIntegrationChannel = function (data) {
        return this.send(Request.put(this.END_POINT + '/integration_channels/' + data.id + '/').data(data.data));
    };
    Api.prototype.deleteIntegrationChannel = function (data) {
        return this.send(Request.del(this.END_POINT + '/integration_channels/' + data.id + '/'));
    };
    Api.prototype.getCounterparties = function () {
        return this.send(Request.get(this.END_POINT + '/organizations/self/counterparties/'));
    };
    Api.prototype.getDomains = function () {
        return this.send(Request.get(this.END_POINT + '/domains/'));
    };
    Api.prototype.getDomain = function (domainId) {
        return this.send(Request.get(this.END_POINT + '/domains/' + domainId + '/'));
    };
    Api.prototype.createFolder = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/').data(data.data));
    };
    Api.prototype.createDomain = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/').data(data.data));
    };
    Api.prototype.updateDomain = function (data) {
        return this.send(Request.put(this.END_POINT + '/domains/' + data.domainId + '/').data(data.data));
    };
    Api.prototype.removeDomain = function (domainId) {
        return this.send(Request.del(this.END_POINT + '/domains/' + domainId + '/'));
    };
    Api.prototype.disableDomain = function (data) {
        return this.send(Request.del(this.END_POINT + '/domains/' + data.domainId + '/').data(data.data));
    };
    Api.prototype.getDomainPages = function (domainId) {
        return this.send(Request.get(this.END_POINT + '/domains/' + domainId + '/page_access/'));
    };
    Api.prototype.getDomainsAndPages = function (client) {
        if (!client) {
            client = '';
        }
        return this.send(Request.get(this.END_POINT + '/domain_page_access/').params({ client: client }));
    };
    Api.prototype.getPage = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/id/' + data.domainId + '/page_content/id/' + data.pageId + '/').params({
            client_seq_no: data.seq_no,
        }));
    };
    Api.prototype.getPageByName = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/name/' + data.domainId + '/page_content/name/' + data.pageId + '/').params({ client_seq_no: data.seq_no }));
    };
    Api.prototype.getPageByUuid = function (data) {
        return this.send(Request.get(this.END_POINT + '/internal/page_content/' + data.uuid + '/').params({
            client_seq_no: data.seq_no,
        }));
    };
    Api.prototype.getPageVerions = function (data) {
        return this.send(Request.get(this.END_POINT + '/page/id/' + data.pageId + '/versions/').params({
            before: data.before,
            after: data.after,
            max: data.max,
            page: data.page,
        }));
    };
    Api.prototype.getPageVerion = function (data) {
        return this.send(Request.get(this.END_POINT + '/page/id/' + data.pageId + '/version/' + data.seqNo + '/'));
    };
    Api.prototype.restorePageVerion = function (data) {
        return this.send(Request.put(this.END_POINT + '/page/id/' + data.pageId + '/version/' + data.seqNo + '/restore/'));
    };
    Api.prototype.getPageAccess = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/id/' + data.domainId + '/page_access/id/' + data.pageId + '/'));
    };
    Api.prototype.getPageWebhooks = function (data) {
        return this.send(Request.get(this.END_POINT + '/page/' + data.pageId + '/webhooks/'));
    };
    Api.prototype.createPageWebhook = function (data) {
        return this.send(Request.post(this.END_POINT + '/page/' + data.pageId + '/webhooks/').data(data.data));
    };
    Api.prototype.getPageWebhook = function (data) {
        return this.send(Request.get(this.END_POINT + '/webhook/' + data.id + '/'));
    };
    Api.prototype.savePageWebhook = function (data) {
        return this.send(Request.put(this.END_POINT + '/webhook/' + data.id + '/').data(data.data));
    };
    Api.prototype.deletePageWebhook = function (data) {
        return this.send(Request.del(this.END_POINT + '/webhook/' + data.id + '/'));
    };
    Api.prototype.getPageById = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/' + data.domainId + '/pages/' + data.pageId + '/'));
    };
    Api.prototype.createPage = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/' + data.domainId + '/pages/').data(data.data));
    };
    Api.prototype.createPageNotification = function (data) {
        return this.send(Request.post(this.END_POINT + '/page/' + data.pageId + '/notification/').data(data.data));
    };
    Api.prototype.createPageContentNotification = function (data) {
        return this.send(Request.post(this.END_POINT + '/page/' + data.pageId + '/content_notification/').data(data.data));
    };
    Api.prototype.createPageNotificationByUuid = function (data) {
        return this.send(Request.post(this.END_POINT + '/page/' + data.uuid + '/notification/').data(data.data));
    };
    Api.prototype.createAnonymousPage = function (data) {
        return this.send(Request.post(this.END_POINT + '/anonymous/page/').data(data.data));
    };
    Api.prototype.queryPageContent = function (data) {
        return this.send(Request.put(this.END_POINT + '/page/' + data.pageId + '/query/').data(data.data));
    };
    Api.prototype.savePageContent = function (data) {
        return this.send(Request.put(this.END_POINT + '/domains/id/' + data.domainId + '/page_content/id/' + data.pageId + '/').data(data.data));
    };
    Api.prototype.savePageContentDelta = function (data) {
        return this.send(Request.put(this.END_POINT + '/domains/id/' + data.domainId + '/page_content_delta/id/' + data.pageId + '/').data(data.data));
    };
    Api.prototype.savePageSettings = function (data) {
        return this.send(Request.put(this.END_POINT + '/domains/' + data.domainId + '/pages/' + data.pageId + '/').data(data.data));
    };
    Api.prototype.deletePage = function (data) {
        return this.send(Request.del(this.END_POINT + '/domains/' + data.domainId + '/pages/' + data.pageId + '/'));
    };
    Api.prototype.saveUserInfo = function (data) {
        return this.send(Request.put(this.END_POINT + '/users/self/').data(data));
    };
    Api.prototype.getUserMetaData = function (data) {
        return this.send(Request.get(this.END_POINT + '/users/' + data.userId + '/meta/').data(data.data));
    };
    Api.prototype.saveUserMetaData = function (data) {
        return this.send(Request.put(this.END_POINT + '/users/' + data.userId + '/meta/').data(data.data));
    };
    Api.prototype.deleteUserMetaData = function (data) {
        return this.send(Request.del(this.END_POINT + '/users/' + data.userId + '/meta/').data(data.data));
    };
    Api.prototype.changePassword = function (data) {
        return this.send(Request.put(this.END_POINT + '/credentials/self/').data(data));
    };
    Api.prototype.changeEmail = function (data) {
        return this.send(Request.put(this.END_POINT + '/credentials/self/').data(data));
    };
    Api.prototype.forgotPassword = function (data) {
        return this.send(Request.post(this.END_POINT + '/password_reset/').data(data));
    };
    Api.prototype.resetPassword = function (data) {
        return this.send(Request.post(this.END_POINT + '/password_reset/confirm/').data(data));
    };
    Api.prototype.inviteUsers = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/' + data.domainId + '/invitations/').data(data.data));
    };
    Api.prototype.acceptInvitation = function (data) {
        return this.send(Request.post(this.END_POINT + '/users/invitation/confirm/').data(data));
    };
    Api.prototype.refuseInvitation = function (data) {
        return this.send(Request.del(this.END_POINT + '/users/invitation/confirm/').data(data));
    };
    Api.prototype.domainInvitations = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/' + data.domainId + '/invitations/').params({ is_complete: 'False' }));
    };
    Api.prototype.userInvitations = function () {
        return this.send(Request.get(this.END_POINT + '/users/self/invitations/').params({ is_complete: 'False' }));
    };
    Api.prototype.domainAccessLog = function (data) {
        return this.send(Request.get(this.END_POINT + '/domain_access/' + data.domainId + '/events/').params({
            page_size: data.limit,
        }));
    };
    Api.prototype.domainUsers = function (data) {
        return this.send(Request.get(this.END_POINT + '/domain_access/' + data.domainId + '/users/'));
    };
    Api.prototype.signupUser = function (data) {
        return this.send(Request.post(this.END_POINT + '/users/signup/').data(data));
    };
    Api.prototype.activateUser = function (data) {
        return this.send(Request.post(this.END_POINT + '/users/signup/confirm/').data(data));
    };
    Api.prototype.setDomainDefault = function (data) {
        return this.send(Request.put(this.END_POINT + '/domain_access/' + data.domainId + '/users/self/').data(data.data));
    };
    Api.prototype.resendInvite = function (data) {
        return this.send(Request.put(this.END_POINT + '/domains/' + data.domainId + '/invitations/' + data.inviteId + '/resend/'));
    };
    Api.prototype.updateDomainAccess = function (data) {
        return this.send(Request.put(this.END_POINT + '/domain_access/' + data.domainId + '/users/').data(data.data));
    };
    Api.prototype.removeUsersFromDomain = function (data) {
        return this.send(Request.del(this.END_POINT + '/domain_access/' + data.domainId + '/users/').data(data.data));
    };
    Api.prototype.getInvitation = function (data) {
        return this.send(Request.get(this.END_POINT + '/users/invitations/' + data.token + '/'));
    };
    Api.prototype.cancelInvitations = function (data) {
        return this.send(Request.del(this.END_POINT + '/domains/' + data.domainId + '/invitations/').data(data.data));
    };
    Api.prototype.getDomainNotificationDestinations = function (data) {
        return this.send(Request.get(this.END_POINT + '/notification/user/self/destinations/'));
    };
    Api.prototype.createDomainNotificationDestination = function (data) {
        return this.send(Request.post(this.END_POINT + '/notification/user/self/destinations/').data(data.data));
    };
    Api.prototype.updateDomainNotificationDestination = function (data) {
        return this.send(Request.put(this.END_POINT + '/notification/user_destination/' + data.id + '/').data(data.data));
    };
    Api.prototype.removeDomainNotificationDestination = function (data) {
        return this.send(Request.del(this.END_POINT + '/notification/user_destination/' + data.id + '/'));
    };
    Api.prototype.getUserSymphonyStreams = function (data) {
        return this.send(Request.get(this.END_POINT + '/notification/user/self/symphony_streams/').params(data && data.params ? data.params : {}));
    };
    Api.prototype.getDomainAccessGroups = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/' + data.domainId + '/access_groups/'));
    };
    Api.prototype.getDomainAccessGroup = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/' + data.domainId + '/access_groups/' + data.groupId + '/'));
    };
    Api.prototype.addDomainAccessGroup = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/' + data.domainId + '/access_groups/').data(data.data));
    };
    Api.prototype.putDomainAgroupMembers = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/' + data.domainId + '/access_groups/' + data.agroupId + '/members/').data(data.data));
    };
    Api.prototype.putDomainAgroupPages = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/' + data.domainId + '/access_groups/' + data.agroupId + '/pages/').data(data.data));
    };
    Api.prototype.updateDomainAgroup = function (data) {
        return this.send(Request.put(this.END_POINT + '/domains/' + data.domainId + '/access_groups/' + data.agroupId + '/').data(data.data));
    };
    Api.prototype.deleteDomainAGroup = function (data) {
        return this.send(Request.del(this.END_POINT + '/domains/' + data.domainId + '/access_groups/' + data.agroupId + '/'));
    };
    Api.prototype.getDomainPageAccess = function (data) {
        return this.send(Request.get(this.END_POINT + '/domain_page_access/' + data.domainId + '/'));
    };
    Api.prototype.getDomainCustomers = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/' + data.domainId + '/customers/'));
    };
    Api.prototype.getDomainUsage = function (data) {
        if (data === void 0) { data = {}; }
        return this.send(Request.get(this.END_POINT + '/domains/id/' + data.domainId + '/usage/').params({
            from_date: data.fromDate,
            to_date: data.toDate,
        }));
    };
    Api.prototype.saveDomainPageAccess = function (data) {
        return this.send(Request.put(this.END_POINT + '/domain_page_access/' + data.domainId + '/basic/').data(data.data));
    };
    Api.prototype.getTemplates = function (data) {
        return this.send(Request.get(this.END_POINT + '/templates/'));
    };
    Api.prototype.saveCustomer = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/' + data.domainId + '/customers/').data(data.data));
    };
    Api.prototype.updateCustomer = function (data) {
        return this.send(Request.put(this.END_POINT + '/domains/' + data.domainId + '/customers/' + data.data.id + '/').data(data.data));
    };
    Api.prototype.removeCustomer = function (data) {
        return this.send(Request.del(this.END_POINT + '/domains/' + data.domainId + '/customers/' + data.customerId + '/'));
    };
    Api.prototype.getDocEmailRules = function (data) {
        return this.send(Request.get(this.END_POINT + '/domains/' + data.domainId + '/docsnames/'));
    };
    Api.prototype.createDocEmailRule = function (data) {
        return this.send(Request.post(this.END_POINT + '/domains/' + data.domainId + '/docsnames/').data(data.data));
    };
    Api.prototype.updateDocEmailRule = function (data) {
        return this.send(Request.put(this.END_POINT + '/domains/' + data.domainId + '/docsnames/' + data.docRuleId + '/').data(data.data));
    };
    Api.prototype.deleteDocEmailRule = function (data) {
        return this.send(Request.del(this.END_POINT + '/domains/' + data.domainId + '/docsnames/' + data.docRuleId + '/'));
    };
    Api.prototype.send = function (request) {
        var _this = this;
        var p = new bluebird_1.default(function (resolve, reject) {
            // Add auth header
            var token = '';
            if (_this.storage) {
                token = _this.storage.persistent.get('access_token');
            }
            if (!token && _this.tokens && _this.tokens.access_token) {
                token = _this.tokens.access_token;
            }
            if (token) {
                request.headers({
                    Authorization: "Bearer " + token,
                });
            }
            // check how long api has been locked
            if (_this._locked && !request.OVERRIDE_LOCK) {
                var date = new Date().getTime();
                if (date > _this._lockedTime.getTime() + _this.lockedTimeCheck) {
                    _this.storage.persistent.remove('renew');
                    _this.unblock();
                    // this.emit(this.EVENT_401);
                }
            }
            // @todo Proper type...
            var provider = _this._locked && !request.OVERRIDE_LOCK ? _this.dummyRequest : _this.request;
            // for now, disabled cache on all requests
            request.cache(false);
            // @todo Add micro time to get requests - !!STUPID IE!!
            /*if (request.METHOD === "GET" && ipp.config.isIE){
                    request.params({ie: new Date().getTime()});
                }*/
            var data = {
                url: request.URL + "?" + _this.helpers.serializeObject(request.PARAMS),
                cache: request.CACHE,
                method: request.METHOD,
                // qs: request.PARAMS,
                data: request.DATA,
                headers: request.HEADERS,
                resolveWithFullResponse: true,
                json: request.JSON,
                responseType: request.RESPONSE_TYPE,
            };
            // dummy request
            if (_this._locked && !request.OVERRIDE_LOCK) {
                provider(data).catch(reject);
                return;
            }
            var req = provider(data, function (err, resp, body) {
                if (err || resp.statusCode >= 300) {
                    if (err) {
                        reject(err);
                    }
                    else {
                        if (!request.JSON) {
                            try {
                                body = JSON.parse(body);
                            }
                            catch (e) {
                                body = {};
                            }
                        }
                        var message = _this.utils.parseApiError({ data: body }, 'Error');
                        var error = new ApiError({
                            method: resp.method,
                            data: body,
                            code: resp.statusCode,
                            statusCode: resp.statusCode,
                            httpCode: resp.statusCode,
                            error: message,
                            httpText: message,
                            message: message
                        });
                        // Emit 401
                        if (error.code === 401 && !_this._locked && error.data.error !== 'invalid_grant') {
                            _this.emit(_this.EVENT_401);
                        }
                        // let errMsg: any = new Error(err.message);
                        reject(error);
                    }
                }
                else {
                    if (!request.JSON) {
                        try {
                            resp.body = JSON.parse(resp.body);
                        }
                        catch (e) {
                            resp.body = {};
                        }
                    }
                    resolve(_this.handleSuccess(resp));
                }
            });
            _this.req = req;
            _this.emit(_this.EVENT_REQ, req);
        });
        return p;
    };
    Api.prototype.getApplicationPageList = function (client) {
        if (client === void 0) { client = ''; }
        return this.send(Request.get(this.END_POINT + '/application_page_list/').params({
            client: client,
        }));
    };
    Api.prototype.getOrganization = function (data) {
        return this.send(Request.get(this.END_POINT + '/organizations/' + data.organizationId + '/'));
    };
    Api.prototype.getOrganizationMetaData = function (data) {
        return this.send(Request.get(this.END_POINT + '/organizations/' + data.organizationId + '/meta/').data(data.data));
    };
    Api.prototype.saveOrganizationMetaData = function (data) {
        return this.send(Request.put(this.END_POINT + '/organizations/' + data.organizationId + '/meta/').data(data.data));
    };
    Api.prototype.deleteOrganizationMetaData = function (data) {
        return this.send(Request.del(this.END_POINT + '/organizations/' + data.organizationId + '/meta/').data(data.data));
    };
    Api.prototype.getOrganizationUsers = function (data) {
        return this.send(Request.get(this.END_POINT + '/organizations/' + data.organizationId + '/users/').params({
            query: data.query,
        }));
    };
    Api.prototype.getOrganizationUsage = function (data) {
        if (data === void 0) { data = {}; }
        return this.send(Request.get(this.END_POINT + '/organizations/self/usage/').params({
            from_date: data.fromDate,
            to_date: data.toDate,
        }));
    };
    Api.prototype.getOrganizationUser = function (data) {
        return this.send(Request.get(this.END_POINT + '/organizations/' + data.organizationId + '/users/' + data.userId + '/'));
    };
    Api.prototype.createOrganizationUser = function (data) {
        return this.send(Request.post(this.END_POINT + '/organizations/' + data.organizationId + '/users/').data(data.data));
    };
    Api.prototype.saveOrganizationUser = function (data) {
        return this.send(Request.put(this.END_POINT + '/organizations/' + data.organizationId + '/users/' + data.userId + '/').data(data.data));
    };
    Api.prototype.getOrganizationDomains = function (data) {
        return this.send(Request.get(this.END_POINT + '/organizations/' + data.organizationId + '/domains/'));
    };
    Api.prototype.getOrganizationDomain = function (data) {
        return this.send(Request.get(this.END_POINT + '/organizations/' + data.organizationId + '/domains/' + data.domainId + '/'));
    };
    Api.prototype.createOrganizationDomain = function (data) {
        return this.send(Request.post(this.END_POINT + '/organizations/' + data.organizationId + '/domains/').data(data.data));
    };
    Api.prototype.saveOrganizationDomain = function (data) {
        return this.send(Request.put(this.END_POINT + '/organizations/' + data.organizationId + '/domains/' + data.domainId + '/').data(data.data));
    };
    Api.prototype.getSsoStatus = function (email) {
        return this.send(Request.get(this.END_POINT + '/sso/status/').params({
            user: email,
        }));
    };
    Api.prototype.downloadPage = function (data) {
        var url = this.END_POINT + "/page/" + data.pageId;
        // if (data.type === 8) {
        //   url += `/query/`
        // } else {
        url += "/download/";
        // }
        return this.send(Request.get(url)
            .params({
            type: 'excel',
            header_row: data.header === undefined ? 'true' : 'false',
            live: data.live === undefined ? 'true' : 'false',
            snapshot: data.snapshot === undefined ? 'true' : 'false',
        })
            .headers({
        // "Content-Disposition": "attachment; filename='test.xlxs'",
        // "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        })
            .responseType('arraybuffer'));
    };
    Api.prototype.getTokens = function () {
        return this.send(Request.get(this.END_POINT + '/credentials/client_app_access/token/self/'));
    };
    Api.prototype.generateToken = function () {
        return this.send(Request.post(this.END_POINT + '/credentials/client_app_access/token/self/'));
    };
    Api.prototype.deleteToken = function (id) {
        return this.send(Request.del(this.END_POINT + '/credentials/client_app_access/token/' + id));
    };
    //Page Schema
    Api.prototype.getSchemas = function () {
        return this.send(Request.get(this.END_POINT + '/organizations/self/page_schemas'));
    };
    Api.prototype.getSingleSchema = function (id) {
        return this.send(Request.get(this.END_POINT + '/page_schemas/' + id));
    };
    Api.prototype.createSchema = function (data) {
        return this.send(Request.post(this.END_POINT + '/organizations/self/page_schemas/').data(data));
    };
    Api.prototype.updateSchema = function (id, data) {
        return this.send(Request.put(this.END_POINT + '/page_schemas/' + id).data(data));
    };
    Api.prototype.deleteSchema = function (id) {
        return this.send(Request.del(this.END_POINT + '/page_schemas/' + id));
    };
    // SDL get history
    Api.prototype.getConnectedHistory = function (id) {
        return this.send(Request.get(this.END_POINT + ("/connected_page/message_history/page_id/" + id + "/?max=10")));
    };
    //Workflow Types
    Api.prototype.getWorkflowTypes = function () {
        return this.send(Request.get(this.END_POINT + "/organizations/self/workflow_types"));
    };
    Api.$inject = [
        '$httpParamSerializerJQLike',
        '$q',
        'ippStorageService',
        'ippConfig',
        'ippUtilsService',
        'ippReqService',
    ];
    return Api;
}(Emitter_1.default));
exports.Api = Api;
//# sourceMappingURL=Api.js.map