"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    APIClient: ()=>APIClient
});
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const sdk_namespaceObject = require("@tachybase/sdk");
const external_antd_namespaceObject = require("antd");
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
function notify(type, messages, instance) {
    var _messages_map;
    if (!(null == messages ? void 0 : messages.length)) return;
    instance[type]({
        message: null === (_messages_map = messages.map) || void 0 === _messages_map ? void 0 : _messages_map.call(messages, (item, index)=>external_react_default().createElement('div', {
                key: "".concat(index, "_").concat(item.message)
            }, 'string' == typeof item ? item : item.message))
    });
}
const handleErrorMessage = (error, notification)=>{
    var _error_response;
    const reader = new FileReader();
    reader.readAsText(null == error ? void 0 : null === (_error_response = error.response) || void 0 === _error_response ? void 0 : _error_response.data, 'utf-8');
    reader.onload = function() {
        const messages = JSON.parse(reader.result).errors;
        notify('error', messages, notification);
    };
};
function offsetToTimeZone(offset) {
    const hours = Math.floor(Math.abs(offset));
    const minutes = Math.abs(offset % 1 * 60);
    const formattedHours = (hours < 10 ? '0' : '') + hours;
    const formattedMinutes = (minutes < 10 ? '0' : '') + minutes;
    const sign = offset >= 0 ? '+' : '-';
    return sign + formattedHours + ':' + formattedMinutes;
}
const getCurrentTimezone = ()=>{
    const timezoneOffset = new Date().getTimezoneOffset() / -60;
    return offsetToTimeZone(timezoneOffset);
};
const errorCache = new Map();
class APIClient extends sdk_namespaceObject.APIClient {
    cloneInstance() {
        const api = new APIClient(this.options);
        api.options = this.options;
        api.services = this.services;
        api.storage = this.storage;
        api.app = this.app;
        api.auth = this.auth;
        api.notification = this.notification;
        const handlers = [];
        for (const handler of this.axios.interceptors.response['handlers'])if ('handleNotificationError' === handler.rejected['_name']) handlers.push({
            ...handler,
            rejected: api.handleNotificationError.bind(api)
        });
        else handlers.push(handler);
        api.axios.interceptors.response['handlers'] = handlers;
        return api;
    }
    getHeaders() {
        var _this_app, _window_location, _window;
        const headers = super.getHeaders();
        const appName = null === (_this_app = this.app) || void 0 === _this_app ? void 0 : _this_app.getName();
        if (appName) headers['X-App'] = appName;
        headers['X-Timezone'] = getCurrentTimezone();
        headers['X-Hostname'] = null === (_window = window) || void 0 === _window ? void 0 : null === (_window_location = _window.location) || void 0 === _window_location ? void 0 : _window_location.hostname;
        return headers;
    }
    service(uid) {
        return this.services[uid];
    }
    interceptors() {
        this.axios.interceptors.request.use((config)=>{
            config.headers['X-With-ACL-Meta'] = true;
            const headers = this.getHeaders();
            Object.keys(headers).forEach((key)=>{
                config.headers[key] = config.headers[key] || headers[key];
            });
            return config;
        });
        super.interceptors();
        this.useNotificationMiddleware();
        this.axios.interceptors.response.use((response)=>response, (error)=>{
            const errs = this.toErrMessages(error);
            if (errs.find((error)=>'ROLE_NOT_FOUND_ERR' === error.code)) {
                this.auth.setRole(null);
                window.location.reload();
            }
            if (errs.find((error)=>'TOKEN_INVALID' === error.code || 'USER_LOCKED' === error.code)) this.auth.setToken(null);
            if (errs.find((error)=>'ROLE_NOT_FOUND_FOR_USER' === error.code)) {
                this.auth.setRole(null);
                window.location.reload();
            }
            throw error;
        });
    }
    toErrMessages(error) {
        var _error_response, _error_response_data, _error_response1, _error_response_data1, _error_response2, _error_response3;
        if ('string' == typeof (null == error ? void 0 : null === (_error_response = error.response) || void 0 === _error_response ? void 0 : _error_response.data)) {
            var _error_response4;
            const tempElement = document.createElement('div');
            tempElement.innerHTML = null == error ? void 0 : null === (_error_response4 = error.response) || void 0 === _error_response4 ? void 0 : _error_response4.data;
            return [
                {
                    message: tempElement.textContent || tempElement.innerText
                }
            ];
        }
        return (null == error ? void 0 : null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : null === (_error_response_data = _error_response1.data) || void 0 === _error_response_data ? void 0 : _error_response_data.errors) || (null == error ? void 0 : null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : null === (_error_response_data1 = _error_response2.data) || void 0 === _error_response_data1 ? void 0 : _error_response_data1.messages) || (null == error ? void 0 : null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : _error_response3.error) || [
            {
                message: error.message || 'Server error'
            }
        ];
    }
    async handleNotificationError(error) {
        var _error_config, _error_response_data, _error_response, _error_response_data1, _error_response1;
        if (this.silence) throw error;
        const skipNotify = null === (_error_config = error.config) || void 0 === _error_config ? void 0 : _error_config.skipNotify;
        if (skipNotify && ('function' == typeof skipNotify && skipNotify(error) || true === skipNotify)) throw error;
        const redirectTo = null == error ? void 0 : null === (_error_response = error.response) || void 0 === _error_response ? void 0 : null === (_error_response_data = _error_response.data) || void 0 === _error_response_data ? void 0 : _error_response_data.redirectTo;
        if (redirectTo) return window.location.href = redirectTo;
        if ((null == error ? void 0 : null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : null === (_error_response_data1 = _error_response1.data) || void 0 === _error_response_data1 ? void 0 : _error_response_data1.type) === 'application/json') handleErrorMessage(error, this.notification);
        else {
            var _error_response_data_error, _error_response_data2, _error_response2;
            if (errorCache.size > 10) errorCache.clear();
            const maintaining = !!(null == error ? void 0 : null === (_error_response2 = error.response) || void 0 === _error_response2 ? void 0 : null === (_error_response_data2 = _error_response2.data) || void 0 === _error_response_data2 ? void 0 : null === (_error_response_data_error = _error_response_data2.error) || void 0 === _error_response_data_error ? void 0 : _error_response_data_error.maintaining);
            if (this.app.maintaining !== maintaining) this.app.maintaining = maintaining;
            if (this.app.maintaining) {
                var _error_response_data3, _error_response3;
                this.app.error = null == error ? void 0 : null === (_error_response3 = error.response) || void 0 === _error_response3 ? void 0 : null === (_error_response_data3 = _error_response3.data) || void 0 === _error_response_data3 ? void 0 : _error_response_data3.error;
                throw error;
            }
            if (this.app.error) this.app.error = null;
            let errs = this.toErrMessages(error);
            errs = errs.filter((error)=>{
                const lastTime = errorCache.get(error.message);
                if (lastTime && new Date().getTime() - lastTime < 500) return false;
                errorCache.set(error.message, new Date().getTime());
                return true;
            });
            if (0 === errs.length) throw error;
            notify('error', errs, this.notification);
        }
        throw error;
    }
    useNotificationMiddleware() {
        const errorHandler = this.handleNotificationError.bind(this);
        errorHandler['_name'] = 'handleNotificationError';
        this.axios.interceptors.response.use((response)=>{
            var _response_data_messages, _response_data;
            if (null === (_response_data = response.data) || void 0 === _response_data ? void 0 : null === (_response_data_messages = _response_data.messages) || void 0 === _response_data_messages ? void 0 : _response_data_messages.length) {
                const messages = response.data.messages.filter((item)=>{
                    const lastTime = errorCache.get('string' == typeof item ? item : item.message);
                    if (lastTime && new Date().getTime() - lastTime < 500) return false;
                    errorCache.set(item.message, new Date().getTime());
                    return true;
                });
                notify('success', messages, this.notification);
            }
            return response;
        }, errorHandler);
    }
    silent() {
        const api = this.cloneInstance();
        api.silence = true;
        return api;
    }
    constructor(...args){
        super(...args), _define_property(this, "services", {}), _define_property(this, "silence", false), _define_property(this, "app", void 0), _define_property(this, "notification", external_antd_namespaceObject.notification);
    }
}
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
