import axios from 'axios';
import { Cookies } from 'react-cookie';
import Router from 'next/router';
import moment from 'moment';

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 sendEmailCheck = ({ email }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/recovery/check`, { email })
		.then((response) => 
		{
			console.log("sendEmailCheck RESPONSE");
			console.log(response.data);

			if(response.data)
			{
				console.log("DATA? ");
				resolve();
			}
			else
			{
				console.log("DATA ! ");
				reject();
			}
		})
		.catch((error) => 
		{
			console.error("error");
			console.error(error);

			reject();
		});
	});
}

export const sendEmailCode = ({ email, code }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/recovery/code`, { email, code })
		.then((response) => 
		{
			console.log("checkSmsCode RESPONSE");
			console.log(response.data);

			if(response.data.status === "success")
			{
				resolve();
			}
			else
			{
				reject();
			}
		})
		.catch((error) => 
		{
			console.error("error");
			console.error(error);

			reject();
		});
	});
}

export const sendPassword = ({ email, code, password, password_repeat }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/recovery/password`, { email, code, password, password_repeat })
		.then((response) => 
		{
			console.log("sendPassword RESPONSE");
			console.log(response.data);

			if(response.data.status === "success")
			{
				resolve();
			}
			else
			{
				reject();
			}
		})
		.catch((error) => 
		{
			console.error("error");
			console.error(error);

			reject();
		});
	});
}

export const sendNewPassword = ({ password, new_password, new_password_repeat }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/change/password`, { password, new_password, new_password_repeat })
		.then((response) => 
		{
			console.log("sendNewPassword RESPONSE");
			console.log(response.data);

			if(response.data.status === "success")
			{
				resolve();
			}
			else
			{
				reject();
			}
		})
		.catch((error) => 
		{
			console.error("error");
			console.error(error);

			reject();
		});
	});
}