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

export const getCalendar = ({ dispatch, date_from, date_to }) => 
{
	console.log("getCalendar", date_from, date_to);
	return new Promise((resolve, reject) => 
	{
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/calendar`, {}, 
		{
			withCredentials: true, 
		})
		.then((response) => 
		{
			const periods = {};

			concatSeries(response.data, (contract, callback) => 
			{
				let payments = [];
				for(let i in contract.payments)
				{
					if(contract.payments[i].date !== null)
					{
						const mdate = moment(contract.payments[i].date, "DD-MM-YYYY");
						periods[mdate.format('YYYYMM')] = mdate.format('YYYYMM');
	
						payments.push({ ...contract.payments[i], ...{ contract: { number: contract.number, date: contract.date }, date: mdate.format("YYYY-MM-DD"), js_date: mdate.toDate() } });
					}
				}

				let query = nSQL(payments)
				.query("select")
				.where([ [ "js_date", ">=", date_from ], "AND", [ "js_date", "<=", date_to ] ])
				.orderBy("number", "asc")
				.exec().then((rows) => 
				{
					callback(null, rows);
				});
			}, (error, result) => 
			{
				let calendar = [];
				nSQL(result)
				.query("select", ["date", "SUM(total_amount) AS total"])
				.groupBy(["date ASC"])
				.exec().then(async (grouped_rows) => 
				{
					for(let i in grouped_rows)
					{
						const payments = await nSQL(result).query("select").where([[ "date", "=", grouped_rows[i].date ]]).exec();

						calendar.push({ ...grouped_rows[i], ...{ payments: payments }});
					}

					console.log("TOTAL calendar", calendar);
					dispatch({ type: actionTypes.CALENDAR, data: { payments: calendar, periods: periods } });
				});
			});

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