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]);
			}
		}
	};	
}

function _getMarks(query, content)
{
	let new_content = content;
	const search_array = query.split(" ");
	for(let s in search_array)
	{ 
		const chunk = search_array[s];
		const s_regex = new RegExp(chunk, 'gim');

		new_content = new_content.replace(s_regex, `<mark>${ chunk }</mark>`)
	}

	return new_content;
}

export const setAppealsRead = ({ dispatch, appeals }) => 
{
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/support/read`, { appeals }, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			dispatch({ type: actionTypes.SUPPORT_APPEALS, data: { appeals: { new: 0, } } });
			resolve();
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});
	});
}

export const getAppeals = ({ dispatch }) => 
{
	console.log("ACTION", "support", "getAppeals", `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/support/appeals`);

	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/support/appeals`, {}, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			console.log("getEvents", "response", response.data);
			const events = response.data;
			const filtered_events = [];

			console.log("events");
			console.log(events);

			dispatch({ type: actionTypes.SUPPORT_APPEALS, data: { appeals: { list: response.data.appeals, new: response.data.new, } } });
			resolve();
		})
		.catch((error) => 
		{
			console.log("error");
			console.error(error);

			reject();
		});
	});
}

export const getSupportThemes = ({ dispatch, query, }) => 
{
	console.log("ACTION", "support", "getSupportThemes", { query });

	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/support/themes`, {
			query
		}, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("getContractRules", "response.data", response.data);
			if(query !== undefined)
			{
				const { themes } = response.data;
				const themes_filtered = [];

				for(let t in themes)
				{
					if(themes[t].questions.length > 0)
					{
						const _theme = {
							_name: _getMarks(query, themes[t].name), 
							questions: [], 
						};

						for(let q in themes[t].questions)
						{
							const _question = themes[t].questions[q];
							_question._title = _getMarks(query, themes[t].questions[q].title);
							_question._answer = _getMarks(query, themes[t].questions[q].answer);

							_theme.questions.push(_question);
						}

						themes_filtered.push(_theme);
					}
				}

				dispatch({ type: actionTypes.SUPPORT_THEMES_FILTERED, data: { filtered: themes_filtered } });
			}
			else
			{
				dispatch({ type: actionTypes.SUPPORT_THEMES, data: { themes: response.data.themes } });
			}

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

export const resetFilteredThemes = ({ dispatch }) => 
{
	return new Promise((resolve, reject) => 
	{
		dispatch({ type: actionTypes.SUPPORT_THEMES_FILTERED, data: { filtered: null } });
		resolve();
	});
}

export const sendNewAppeal = (appeal) => 
{
	console.log("ACTION", "support", "sendNewAppeal", appeal);

	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/support/request`, appeal, 
		{
			withCredentials: true, 
		})
		.then(async (response) => 
		{
			console.log("sendNewAppeal", "response.data", response.data);	
			resolve(response.data);
		})
		.catch((error) => 
		{
			console.error(error);
			reject();
		});
	});
}

export const sendAppealAttachments = (payload) => 
{
	console.log("ACTION", "support", "sendAppealAttachments", payload);

	return new Promise((resolve, reject) => 
	{
		eachSeries(payload.files, (file, callback) => 
		{
			let data = new FormData();
			data.append('file', file);

			axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/support/attachment?request_client_number=${ payload.request_client_number }`, data, 
			{
				headers: {
					"Content-Type": "multipart/form-data", 
				}, 
				withCredentials: true, 
			})
			.then(async (response) => 
			{
				console.log("sendAppealAttachments", "response.data", response.data);	
				callback(null);
			})
			.catch((error) => 
			{
				console.error(error);
				callback(true);
			});
		}, (err) => 
		{
			if(!err)
			{
				resolve();
			}
			else
			{
				reject();
			}
		});
	});
}