import axios from 'axios';
import { Cookies } from 'react-cookie';
import Router from 'next/router';
import moment from 'moment';
import { nSQL } from "@nano-sql/core";

import * as actionTypes from '../constants/actionTypes';

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 getEvents = ({ dispatch, type, contract }) => 
{
	console.log("getEvents", `${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/events`);

	return new Promise((resolve, reject) => 
	{
		if(global.store.getState().events.list === undefined)
		{
			axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/events`, {}, {
				withCredentials: true, 
			})
			.then((response) => 
			{
				console.log("ACTION", "getEvents()", "response", response.data);
				const events = response.data;
				const filtered_events = [];
	
				console.log("ACTION", "getEvents()", "events", events);
	
				dispatch({ type: actionTypes.EVENTS, data: { list: events, loaded: true } });
				resolve();
			})
			.catch((error) => 
			{
				console.log("error");
				console.error(error);
	
				reject();
			});
		}
		else
		{
			resolve();
		}
	});
}

export const getFilteredEvents = ({ dispatch, search }) => 
{
	return new Promise((resolve, reject) => 
	{
		console.log("getFilteredEvents");

		const types = {
			"additional": [ "osago_prolong", "kasko_prolong", "fingap_prolong" ], 
			"finance": [ "graph_change", "end_contract" ],  
			"fines": "fine_gibdd", 
			"pts": "return_pts", 
		};

		if((search !== undefined || search !== null || search !== ""))
		{
			console.log(global.store.getState().events);
			const events = global.store.getState().events.list;

			let query = nSQL(events)
			.query("select");

			/*
			if(type !== undefined)
			{
				if(typeof types[ type ] === "string")
				{
					query.where([ [ "event_type", "=", types[ type ] ] ])
				}
				else
				{
					let array_of_queries = [];
					for(let i in types[ type ])
					{
						array_of_queries.push([ "event_type", "=", types[ type ][ i ] ]);
						if(parseInt(i, 10) < parseInt(types[ type ].length - 1))
						{
							console.log(parseInt(i, 10), "<", types[ type ].length - 1);
							array_of_queries.push("OR");
						}
					}
					console.log("array_of_queries", array_of_queries);
					query.where(array_of_queries);
				}
			}
			*/

			if(search !== undefined && search !== null && search !== "")
			{
				query.where([ [ "contract_number", "LIKE", `%${ search }%` ], "OR", [ "add_info", "LIKE", `%${ search }%` ]]);
			}

			query.exec().then((rows) => 
			{
				console.log("rows");
				console.log(rows);
	
				dispatch({ type: actionTypes.EVENTS_FILTERED, data: { filtered: rows } });
				resolve();

			});
		}
		else
		{
			dispatch({ type: actionTypes.EVENTS_FILTERED, data: { filtered: undefined } });
			resolve();
		}
	});
}

export const getContractEvents = ({ dispatch, contract }) => 
{
	return new Promise((resolve, reject) => 
	{
		console.log("getContractEvents");

		console.log(global.store.getState().events);
		const events = global.store.getState().events.list;
	
		let query = nSQL(events)
		.query("select");

		if(contract !== undefined && contract !== null && contract !== "")
		{
			query.where([ [ "contract_number", "=", contract ] ]);
		}

		query.exec().then((rows) => 
		{
			console.log("rows");
			console.log(rows);

			const events_list = {};
			events_list[`${ contract }`] = rows;
	
			dispatch({ type: actionTypes.CONTRACT_EVENTS, data: events_list });	
			resolve();		
		});
	});
}