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';

import { getCompanyInfo } from './companyActions';

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 sendLoginFormEmail = ({ email, password, dispatch }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/account/auth/email/`, { email, password })
		.then((response) => 
		{
			console.log("sendLoginFormEmail RESPONSE");
			console.log(response.data);

			if(response.data.status === "success")
			{
				const cookies = new Cookies();
				cookies.set('jwt', response.data.token, new Date(moment().add(7, 'day').toDate()));

				getCompanyInfo({ dispatch })
				.then(() => 
				{
					dispatch({ type: actionTypes.AUTH, data: { logged: true } });
					dispatch({ type: actionTypes.USER, data: response.data.user });
					dispatch({ type: actionTypes.COMPANIES, data: { list: response.data.companies } });

					resolve();
					Router.push('/');	
				})
				.catch(() => 
				{
					reject();
				});
				//dispatch({ type: actionTypes.COMPANY, data: response.data.company });
			}
			else
			{
				reject();
			}
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});
	});
}

export const sendLoginFormPhone = ({ phone }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/auth/phone/check`, { phone })
		.then((response) => 
		{
			console.log("sendLoginFormPhone RESPONSE");
			console.log(response.data);

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

			reject();
		});
	});
}

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

			if(response.data.status === "success")
			{
				const cookies = new Cookies();
				cookies.set('jwt', response.data.token, new Date(moment().add(7, 'day').toDate()));

				getCompanyInfo({ dispatch })
				.then(() => 
				{
					dispatch({ type: actionTypes.AUTH, data: { logged: true } });
					dispatch({ type: actionTypes.USER, data: response.data.user });	

					resolve();
					Router.push('/');	
				})
				.catch(() => 
				{
					reject();
				});
			}
			else
			{
				reject();
			}
		})
		.catch((error) => 
		{
			console.error("sendSmsCode", "error");
			console.error(error);

			reject();
		});
	});
}

export const logout = ({ dispatch, redirect = true }) => 
{
	return new Promise((resolve, reject) => 
	{
		const cookies = new Cookies();
		cookies.remove('jwt');
		cookies.remove('observer');

		dispatch({ type: actionTypes.AUTH, data: { logged: false, observer: false } });
		dispatch({ type: actionTypes.USER, data: {} });
		dispatch({ type: actionTypes.COMPANY, data: {} });
		dispatch({ type: actionTypes.CONTRACTS_INFO_RESET, data: {} });
		dispatch({ type: actionTypes.EVENTS_RESET, data: {} });
		dispatch({ type: actionTypes.SUPPORT_RESET, data: {} });

		resolve();
		if(redirect)
		{
			Router.push('/');
		}
	});
}

export const sendOffstageToken = ({ token, dispatch }) => 
{
	console.log("ACTION", "sendOffstageToken()", `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/auth/offstage/`);

	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/auth/offstage/`, { token })
		.then((response) => 
		{
			console.log("sendOffstageToken RESPONSE");
			console.log(response.data);

			if(response.data.status === "success")
			{
				const cookies = new Cookies();
				cookies.set('jwt', response.data.token, new Date(moment().add(7, 'day').toDate()));
				cookies.set('observer', true, new Date(moment().add(7, 'day').toDate()));

				getCompanyInfo({ dispatch })
				.then(() => 
				{
					dispatch({ type: actionTypes.AUTH, data: { logged: true, observer: true } });
					dispatch({ type: actionTypes.USER, data: response.data.user });
					dispatch({ type: actionTypes.COMPANIES, data: { list: response.data.companies } });

					resolve();
					Router.push('/');	
				})
				.catch(() => 
				{
					reject();
				});
				//dispatch({ type: actionTypes.COMPANY, data: response.data.company });
			}
			else
			{
				reject();
			}
		})
		.catch((error) => 
		{
			console.error("sendOffstageToken", "error");
			console.error(error);

			reject();
		});
	});
}

export const sendSwitchAccount = ({ dispatch, acc_number }) => 
{
	console.log("ACTION", "sendSwitchAccount()", `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/auth/switch/`);

	dispatch({ type: actionTypes.USER, data: {} });
	dispatch({ type: actionTypes.COMPANY, data: {} });
	dispatch({ type: actionTypes.CONTRACTS_INFO_RESET, data: {} });
	dispatch({ type: actionTypes.EVENTS_RESET, data: {} });
	dispatch({ type: actionTypes.SUPPORT_RESET, data: {} });

	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/auth/switch/`, { acc_number })
		.then((response) => 
		{
			console.log("sendSwitchAccount RESPONSE");
			console.log(response.data);

			if(response.data.status === "success")
			{
				const cookies = new Cookies();
				cookies.set('jwt', response.data.token, new Date(moment().add(7, 'day').toDate()));

				getCompanyInfo({ dispatch })
				.then(() => 
				{
					resolve();
					Router.push('/');	
				})
				.catch(() => 
				{
					reject();
				});
			}
			else
			{
				reject();
			}
		})
		.catch((error) => 
		{
			console.error("sendSwitchAccount", "error");
			console.error(error);

			reject();
		});
	});
}