// export type AxiosJsonResponseType<T = any> = AxiosPromise<T>;
var cid = 1;
export default function jsonpAdapter(config) {
    return new Promise(function (resolve, reject) {
        if (!config.url)
            return reject(new Error('Url not given, or empty'));
        //define script
        var script = document.createElement('script');
        script.async = true;
        script.onload = script.onreadystatechange = function () {
            if (!(script === null || script === void 0 ? void 0 : script.readyState) || /loaded|complete/.test(script.readyState))
                remove();
        };
        script.onerror = function () {
            remove();
            reject(new Error('Network Error'));
        };
        var jsonp = 'axiosJsonpCallback' + cid++;
        var old = window[jsonp];
        var isAbort = false;
        window[jsonp] = function (responseData) {
            window[jsonp] = old;
            if (isAbort)
                return;
            resolve({
                data: responseData,
                status: 200,
            });
        };
        var src = config.url;
        if (config.params) {
            var params = buildParams(config.params);
            if (params)
                src += (src.indexOf('?') >= 0 ? '&' : '?') + params;
        }
        var additionalParams = {
            _: new Date().getTime(),
        };
        additionalParams[config.callbackParamName || 'callback'] = jsonp;
        src += (src.indexOf('?') >= 0 ? '&' : '?') + buildParams(additionalParams);
        if (config.cancelToken) {
            config.cancelToken.promise.then(function (cancel) {
                if (!script)
                    return;
                isAbort = true;
                reject(cancel);
            });
        }
        script.src = src;
        document.head.appendChild(script);
        function remove() {
            if (!script)
                return;
            script.onload = script.onreadystatechange = script.onerror = null;
            if (script.parentNode)
                script.parentNode.removeChild(script);
            script = null;
        }
    });
}
var buildParams = function (params) { return new URLSearchParams(params).toString(); }; //.replaceAll('+', '%20');
