import axios from 'axios';
import fileDownload from 'js-file-download';

import * as actionTypes from '../constants/actionTypes';

if(process.browser)
{
	FormData.prototype.appendObject = function(obj, namespace) 
	{
		let keyName;
		for (var key in obj) 
		{
			if (obj.hasOwnProperty(key)) 
			{
				keyName = [namespace, '[', key, ']'].join('');
				this.append(keyName, obj[key]);
			}
		}
	};	
}

export const getContractInvoices = ({ dispatch, number }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/invoices`, { number }, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("getContractInvoices", { response: response.data });
			dispatch({ type: actionTypes.INVOICES_LIST, data: { number, invoices: response.data } });
			resolve();
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});
	});
}

export const downloadInvoiceFile = ({ payload, filename }) => 
{
	const url = `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/invoice/download`;

	return new Promise((resolve, reject) => 
	{
		axios.get(url, {
			params: payload, 
			responseType: 'blob', 
		})
		.then((response) => 
		{
			fileDownload(response.data, filename);
			resolve();
		})
		.catch((error) => 
		{
			console.error("ACTION", "sign", "downloadInvoiceFile()", "ERROR");
			console.error(error);

			const eventMessage = new CustomEvent("_message", { detail: { type: "error", title: "Ошибка", content: "Ошибка при вызове метода GetWMDoc" } });
			window.dispatchEvent(eventMessage);

			reject(error.data);
		});
	});
}

export const getInvoiceKASKO = ({ number }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/invoice/kasko`, { number }, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("getInvoiceKASKO", { response: response.data });
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});
	});
}

export const getInvoiceFinGap = ({ number }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/invoice/fingap`, { number }, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("getInvoiceFinGap", { response: response.data });
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});
	});
}