import axios from 'axios';
import { Cookies } from 'react-cookie';
import Router from 'next/router';
import moment from 'moment';
import { nSQL } from "@nano-sql/core";
import { eachSeries } from 'async';
import fileDownload from 'js-file-download';

import * as actionTypes from '../constants/actionTypes';
import * as currentState from '../reducers/initialState';

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 getDeals = ({ dispatch, update = false }) => 
{
	const url = `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals`;

	console.log("ACTION", "deals", "getDeals()", { url });

	return new Promise((resolve, reject) => 
	{
		let last = 0;

		axios.post(url, {}, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			console.log("ACTION", "deals", "getDeals()", "response", response.data);

			for(let i in response.data)
			{
				const n = parseInt(response.data[i].opp_number, 10);

				if(n > last)
				{
					last = n;
				}
			}

			dispatch({ 
				type: actionTypes.DEALS_LIST, 
				data: { 
					list: response.data, 
					last, 
				} 
			});

			resolve();
		})
		.catch((error) => 
		{
			console.error("ACTION", "deals", "getDeals()", "ERROR");
			console.error(error);

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

			dispatch({ 
				type: actionTypes.DEALS_LIST, 
				data: { 
					list: [], 
					last, 
				} 
			});

			reject();
		});
	});
}

export const getDealOffers = ({ dispatch, deal_id }) => 
{
	const url = `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals/offer/list`;

	console.log("ACTION", "deals", "getDealOffers()", { url });
	console.log("ACTION", "deals", "getDealOffers()", { deal_id });

	return new Promise((resolve, reject) => 
	{
		axios.post(url, { deal_id }, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			console.log("ACTION", "deals", "getDealOffers()", "response", response.data);

			dispatch({ 
				type: actionTypes.DEAL_OFFERS_LIST, 
				data: { 
					deal_id, 
					list: response.data
				} 
			});

			resolve();
		})
		.catch((error) => 
		{
			console.error("ACTION", "deals", "getDealOffers()", "ERROR");
			console.error(error);

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

			dispatch({ 
				type: actionTypes.DEAL_OFFERS_LIST, 
				data: { 
					deal_id, 
					list: []
				} 
			});

			reject();
		});
	});
}

export const downloadDealOffer = ({ quote_number, filename }) => 
{
	return new Promise((resolve, reject) => 
	{
		const url = `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals/offer/download`;

		axios.get(url, {
			params: { quote_number }, 
			responseType: 'blob', 
		})
		.then((response) => 
		{
			fileDownload(response.data, filename);
			resolve();
		})
		.catch((error) => 
		{
			console.error("ACTION", "sign", "downloadDealOffer()", "ERROR");
			console.error(error);

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

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

export const acceptDealOffers = ({ deal_id, offers }) => 
{
	const url = `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals/accept`;

	console.log("ACTION", "deals", "acceptDealOffers()", { url });
	console.log("ACTION", "deals", "acceptDealOffers()", { deal_id, offers, });

	return new Promise((resolve, reject) => 
	{
		axios.post(url, { deal_id, offers }, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			console.log("ACTION", "deals", "acceptDealOffers()", "response", response.data);

			resolve();
		})
		.catch((error) => 
		{
			console.error("ACTION", "deals", "acceptDealOffers()", "ERROR");
			console.error(error);

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

			reject();
		});	
	});
}

export const getDealDocuments = ({ dispatch, deal_id }) => 
{
	const url = `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals/documents`;

	console.log("ACTION", "deals", "getDealDocuments()", { url });
	console.log("ACTION", "deals", "getDealDocuments()", { deal_id, });

	return new Promise((resolve, reject) => 
	{
		axios.post(url, { deal_id }, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			console.log("ACTION", "deals", "getDealDocuments()", "response", response.data);

			dispatch({ 
				type: actionTypes.DEAL_DOCUMENTS_LIST, 
				data: { 
					deal_id, 
					documents: response.data.documents, 
					uploaded: response.data.uploaded, 
				} 
			});

			resolve();
		})
		.catch((error) => 
		{
			console.error("ACTION", "deals", "getDealDocuments()", "ERROR");
			console.error(error);

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

			dispatch({ 
				type: actionTypes.DEAL_DOCUMENTS_LIST, 
				data: { 
					deal_id, 
					documents: [], 
					uploaded: {}, 
				} 
			});

			reject();
		});
	});
}

export const sendDealDocuments = ({ deal_id }) => 
{
	return new Promise((resolve, reject) => 
	{
		const payload = {
			deal_id, 
		};

		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals/upload`, payload, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("ACTION", "deals", "sendDealDocuments", "response.data", response.data);

			setTimeout(() => 
			{
				resolve();
			}, 20000);
		})
		.catch((error) => 
		{
			console.error(error);

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

			reject();
		});
	});
}

export const getDealContracts = ({ dispatch, deal_id }) => 
{
	const url = `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals/contracts`;

	console.log("ACTION", "deals", "getDealContracts()", { url });
	console.log("ACTION", "deals", "getDealContracts()", { deal_id, });

	return new Promise((resolve, reject) => 
	{
		axios.post(url, { deal_id }, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			console.log("ACTION", "deals", "getDealContracts()", "response", response.data);

			dispatch({ 
				type: actionTypes.DEAL_CONTRACTS_LIST, 
				data: { 
					deal_id, 
					list: response.data
				} 
			});

			resolve();
		})
		.catch((error) => 
		{
			console.error("ACTION", "deals", "getDealContracts()", "ERROR");
			console.error(error);

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

			dispatch({ 
				type: actionTypes.DEAL_CONTRACTS_LIST, 
				data: { 
					deal_id, 
					list: []
				} 
			});

			reject();
		});
	});
}

export const attachDealDocument = ({ deal_id, document_id, document_name, group, index, lastModified, filename, file, type }) => 
{
	return new Promise((resolve, reject) => 
	{
		let data = new FormData();
		data.append('file', file);

		const payload = new URLSearchParams({
			deal_id, 
			document_id, 
			document_name, 
			group, 
			filename, 
			index, 
			lastModified, 
			type
		});

		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals/file/attach?${ payload.toString() }`, data, 
		{
			headers: {
				"Content-Type": "multipart/form-data", 
			}, 
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("ACTION", "deals", "attachDealDocument", "response.data", response.data);

			resolve();
		})
		.catch((error) => 
		{
			console.error(error);

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

			reject();
		});
	});
}

export const removeDealDocument = ({ deal_id, group, index, }) => 
{
	return new Promise((resolve, reject) => 
	{
		const payload = new URLSearchParams({
			deal_id, 
			group, 
			index, 
		});

		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/deals/file/remove?${ payload.toString() }`, {}, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("ACTION", "deals", "removeDocument", "response.data", response.data);

			resolve();
		})
		.catch((error) => 
		{
			console.error(error);

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

			reject();
		});
	});
}