import {
	parseUrl,
	getHeaders,
	isEmptyObject,
	getCustomHeaders,
	convertArrayToHeaders,
} from '../utils';
import CustomError from '../utils/CustomError';

const testConnection = async (appname, rawUrl) => {
	const defaultError = 'Unable to connect';
	try {
		const { url } = parseUrl(rawUrl);
		const headers = getHeaders(rawUrl);
		const customHeaders = getCustomHeaders(appname);

		const res = await fetch(`${url}/${appname}`, {
			'Content-Type': 'application/json',
			headers: { ...headers, ...convertArrayToHeaders(customHeaders) },
		}).then(response => response.json());

		if (res.status >= 400) {
			throw new CustomError(
				JSON.stringify(res.error, null, 2),
				`HTTP STATUS: ${res.status} - ${defaultError}`,
			);
		}

		if (isEmptyObject(res)) {
			throw new CustomError(
				JSON.stringify(
					{
						error: `Unable to find ${appname}`,
					},
					null,
					2,
				),
				`Error: Index not found`,
			);
		}
		return res;
	} catch (error) {
		console.log(error);
		const err = error;
		if (err.message === 'Failed to fetch') {
			err.message = defaultError;
		}

		throw new CustomError(
			err.description && !isEmptyObject(JSON.parse(err.description))
				? err.description
				: `<b> Possible Errors </b>
				<ul><li>Invalid connection string or index name </li>
				<li> Please check is Elasticsearch cluster is up and running</li></ul>`,
			err.message || defaultError,
			err.stack,
		);
	}
};

export default testConnection;

@@ -975,402 +975,701 @@
 cons
-ole.log(error);%0A%09%09const err = error;%0A%09%09if (err.message === 'Failed to fetch') %7B%0A%09%09%09err.message = defaultError;%0A%09%09%7D%0A%0A%09%09throw new CustomError(%0A%09%09%09err.description && !isEmptyObject(JSON.parse(err.description))%0A%09%09%09%09? err.description%0A%09%09%09%09: %60%3Cb%3E Possible Errors %3C/b%3E%0A%09%09%09%09%3Cul%3E%3Cli%3EInvalid connection string or index name %3C/li%3E%0A%09%09%09%09%3Cli%3E Please check is Elasticsearch cluster is up and running%3C/li%3E%3C/ul%3E%60
+t err = error;%0A%09%09let description = %60%3Cb%3E Possible Errors %3C/b%3E%0A%09%09%3Cul%3E%3Cli%3EInvalid connection string or index name %3C/li%3E%0A%09%09%3Cli%3E Please check is Elasticsearch cluster is up and running%3C/li%3E%3C/ul%3E%60;%0A%0A%09%09if (err.message === 'Failed to fetch') %7B%0A%09%09%09err.message = defaultError;%0A%09%09%7D%0A%0A%09%09if (err.message === 'NetworkError when attempting to fetch resource.') %7B%0A%09%09%09description = %60You are trying to load http content over https.%0A%09%09%09%09You might have to enable mixed content of your browser%0A%09%09%09%09%3Ca target=%22_blank%22 href=%22https://kb.iu.edu/d/bdny%22%3Ehttps://kb.iu.edu/d/bdny%3C/a%3E%60;%0A%09%09%7D%0A%0A%09%09throw new CustomError(%0A%09%09%09err.description && !isEmptyObject(JSON.parse(err.description))%0A%09%09%09%09? err.description%0A%09%09%09%09: description
 ,%0A%09%09

Add custom message for mixed content