import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_sdk__ from "@tachybase/sdk";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "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)=>__WEBPACK_EXTERNAL_MODULE_react__["default"].createElement('div', {}, '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);
    };
};
const errorCache = new Map();
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);
};
class APIClient extends __WEBPACK_EXTERNAL_MODULE__tachybase_sdk__.APIClient {
    service(uid) {
        return this.services[uid];
    }
    getHeaders() {
        var _window_location, _window;
        const headers = super.getHeaders();
        const appName = 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;
    }
    interceptors() {
        this.axios.interceptors.request.use((config)=>{
            config.headers['X-With-ACL-Meta'] = true;
            const appName = this.app ? (0, __WEBPACK_EXTERNAL_MODULE__tachybase_sdk__.getSubAppName)(this.app.getPublicPath()) : null;
            if (appName) config.headers['X-App'] = appName;
            return config;
        });
        super.interceptors();
        this.useNotificationMiddleware();
        this.axios.interceptors.response.use((response)=>response, (error)=>{
            var _error_response_data, _error_response;
            const errs = (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.errors) || [
                {
                    message: 'Server error'
                }
            ];
            if (errs.find((error)=>'ROLE_NOT_FOUND_ERR' === error.code)) this.auth.setRole(null);
            throw error;
        });
    }
    useNotificationMiddleware() {
        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;
        }, (error)=>{
            var _error_response_data, _error_response, _error_response_data1, _error_response1;
            if (this.silence) 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, _error_response_data3, _error_response3, _error_response_data4, _error_response4;
                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_data5, _error_response5;
                    this.app.error = null == error ? void 0 : null === (_error_response5 = error.response) || void 0 === _error_response5 ? void 0 : null === (_error_response_data5 = _error_response5.data) || void 0 === _error_response_data5 ? void 0 : _error_response_data5.error;
                    throw error;
                }
                if (this.app.error) this.app.error = null;
                let errs = (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.errors) || (null == error ? void 0 : null === (_error_response4 = error.response) || void 0 === _error_response4 ? void 0 : null === (_error_response_data4 = _error_response4.data) || void 0 === _error_response_data4 ? void 0 : _error_response_data4.messages) || [
                    {
                        message: 'Server 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;
        });
    }
    silent() {
        this.silence = true;
        return this;
    }
    constructor(...args){
        super(...args), _define_property(this, "services", {}), _define_property(this, "silence", false), _define_property(this, "app", void 0), _define_property(this, "notification", __WEBPACK_EXTERNAL_MODULE_antd__.notification);
    }
}
export { APIClient };
