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 * as actionTypes from '../constants/actionTypes';
import * as currentState from '../reducers/initialState';
import { eachSeries } from 'async';

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 getContract = ({ dispatch, number, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract`, {
			number: number
		}, 
		{
			withCredentials: true, 
		})
		.then((response) => 
		{
			console.log("response.data");
			console.log(response.data);

			dispatch({ type: actionTypes.CONTRACT_PAYMENTS, data: { payments: response.data.payments, avans: response.data.avans } });

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

export const getContractInfo = ({ dispatch, number, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/info`, {
			number: number
		}, 
		{
			withCredentials: true, 
		})
		.then((response) => 
		{
			const info = { date: response.data.dl_date, car: response.data.car };
			dispatch({ type: actionTypes.CONTRACT_INFO, data: info });

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

export const getContractInsurance = ({ dispatch, number, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/insurance`, {
			number: number
		}, 
		{
			withCredentials: true, 
		})
		.then((response) => 
		{
			dispatch({ type: actionTypes.CONTRACT_INSURANCE, data: { insurance: response.data } });

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

export const getContractHelpCard = ({ dispatch, number, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/helpcard`, {
			number: number
		}, 
		{
			withCredentials: true, 
		})
		.then((response) => 
		{
			dispatch({ type: actionTypes.CONTRACT_HELPCARD, data: { helpcard: response.data } });

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

export const getContractRegistration = ({ dispatch, number, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/registration`, {
			number: number
		}, 
		{
			withCredentials: true, 
		})
		.then((response) => 
		{
			dispatch({ type: actionTypes.CONTRACT_REGISTRATION, data: { registration: response.data } });

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

export const getContractTelematic = ({ dispatch, number, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/telematic`, {
			number: number
		}, 
		{
			withCredentials: true, 
		})
		.then((response) => 
		{
			dispatch({ type: actionTypes.CONTRACT_TELEMATIC, data: { telematic: response.data } });

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

export const getContractAgreement = ({ dispatch, number, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/agreement`, {
			number: number
		}, 
		{
			withCredentials: true, 
		})
		.then((response) => 
		{
			dispatch({ type: actionTypes.CONTRACT_AGREEMENT, data: { agreement: response.data } });

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

export const getContractDocuments = ({ dispatch, number, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/documents`, {
			number: number
		}, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{

			console.log("getDocuments", "response.data", response.data);

			const documents = { upd: [], upd_avans: [], fines: [] };

			await Promise.all([
			new Promise((pr) => 
			{
				let query = nSQL(response.data.upd).query("select");
				query = query.orderBy({ date: "desc" });

				query.exec().then((rows) => 
				{
					documents.upd = rows;
					pr();
				});	
			}), new Promise((pr) => 
			{
				let query = nSQL(response.data.upd_avans).query("select");
				query = query.orderBy({ date: "desc" });

				query.exec().then((rows) => 
				{
					documents.upd_avans = rows;
					pr();
				});	
			}), new Promise((pr) => 
			{
				let query = nSQL(response.data.billfines).query("select");
				query = query.orderBy({ date: "desc" });

				query.exec().then((rows) => 
				{
					documents.billfines = rows;
					pr();
				});	
			}), new Promise((pr) => 
			{
				let query = nSQL(response.data.fines).query("select");
				query = query.orderBy({ date: "desc" });

				query.exec().then((rows) => 
				{
					documents.fines = rows;
					pr();
				});	
			})])
			.then(() => 
			{
				console.log("documents");
				console.log(documents);
				dispatch({ type: actionTypes.CONTRACT_DOCUMENTS, data: { documents: documents } });
				resolve();	
			});
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});
	});
}

export const getContractRules = ({ dispatch, date, }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contract/rules`, {
			date: date
		}, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("getContractRules", "response.data", response.data);
			dispatch({ type: actionTypes.CONTRACT_RULES, data: { rules: response.data.rules } });

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

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

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