import axios from 'axios';
import { eachSeries } from 'async';

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 getAddress = (query) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/suggests/address`, { query }, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});
	});
}

export const getFullnamePart = (query, parts) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/suggests/name`, { query, parts }, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});
	});
}

export const getSuggests = (type, payload) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/suggests/${ type }`, payload, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});
	});
}

export const checkDocumentData = (payload) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/suggests/document/check`, payload, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});
	});
}
