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 sendPhoneChangeNumber = ({ email, phone }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/change/phone/send`, { email, phone })
		.then((response) => 
		{
			console.log("\n", "sendLoginFormPhone", "RESPONSE");
			console.log(response.data);

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

			reject();
		});
	});
}

export const sendPhoneChangeNumberSmsCode = ({ phone, code }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/change/phone/code`, { phone, code })
		.then((response) => 
		{
			console.log("\n", "sendPhoneChangeNumberSmsCode", "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 = ({ email, password, new_password, new_password_repeat }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/change/password`, { email, password, new_password, new_password_repeat })
		.then((response) => 
		{
			console.log("\n", "sendNewPassword", "RESPONSE");
			console.log(response.data);

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

			reject();
		});
	});
}

export const setUserPhone = ({ dispatch, user }) => 
{
	console.log("setUserPhone", dispatch, user);
	dispatch({ type: actionTypes.USER, data: user });	
}