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';
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 getContractsList = ({ dispatch, order = "date", sort = "desc", page = 1, search, date_from, date_to, all }) => 
{
	const page_size = 5;

	return new Promise((resolve, reject) => 
	{
		//let cookies = new Cookies();
		//let cookies_list = cookies.getAll();
	
		axios.post(`${ process.env.NEXT_PUBLIC_SELF_API_HOST }/api/contracts`, {}, {
			withCredentials: true, 
		})
		.then((response) => 
		{
			const orderBy = {};
			orderBy[order] = sort;
			const offset = (page - 1) * page_size;

			const contracts = [];
			for(let i in response.data)
			{
				const contract = response.data[i];
				contract.js_date = moment(contract.date, "YYYY-MM-DD").toDate();
				contracts.push(contract);
			}

			let query = nSQL(contracts).query("select");
			let query_total = nSQL(contracts).query("select", ["COUNT(*) AS total"]);

			if(search !== undefined && search !== null && search !== "")
			{
				query = query.where([["number", "LIKE", `%${ search }%`], "OR", ["car.reg_number", "LIKE", `%${ search }%`], "OR", ["car.vin_number", "LIKE", `%${ search }%`], "OR", ["car.brand.name", "LIKE", `%${ search }%`], "OR", ["car.model.name", "LIKE", `%${ search }%`]]);
				query_total = query_total.where([["number", "LIKE", `%${ search }%`], "OR", ["car.reg_number", "LIKE", `%${ search }%`], "OR", ["car.vin_number", "LIKE", `%${ search }%`], "OR", ["car.brand.name", "LIKE", `%${ search }%`], "OR", ["car.model.name", "LIKE", `%${ search }%`]])
			}

			if(date_from !== undefined && date_from !== null && date_from !== "")
			{
				query = query.where([[ "js_date", ">=", date_from ]]);
				query_total = query_total.where([[ "js_date", ">=", date_from ]])
			}

			if(date_to !== undefined && date_to !== null && date_to !== "")
			{
				query = query.where([[ "js_date", "<=", date_to ]]);
				query_total = query_total.where([[ "js_date", "<=", date_to ]])
			}

			if(all)
			{
				query = query.orderBy(orderBy);
			}
			else
			{
				query = query.orderBy(orderBy).limit(page_size).offset(offset);
			}

			query_total.exec().then((total_rows) => 
			{
				const total = total_rows[0].total;
				console.log("total", total);

				query.exec().then((rows) => 
				{
					console.log(rows); // <= [{name: "jeb", age: 27}]
					dispatch({ type: actionTypes.CONTRACTS, data: { list: rows, page: page, pages: Math.ceil(total / page_size) } });
				});
			});

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

		/*
		axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/account/contracts/`, { }, {
			headers: 
			{
				Authorization: `Bearer ${  }`,
			}
		})
		.then((response) => 
		{
			console.log("getContractsList RESPONSE");
			console.log(response.data);

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

			reject();
		});
		*/

		/*
		if(fields.username === "test@test.com" && fields.password === "test")
		{
			const cookies = new Cookies();
			cookies.set('jwt', 1, new Date(moment().add(1, 'day').toDate()));
		}
		Router.push('/');
		*/

		/*
		axios.post(`${ process.env.NEXT_PUBLIC_API_HOST }/api/forms/terms/`, fields)
		.then((response) => 
		{
			console.log("sendTermsForm RESPONSE");
			console.log(response.data);

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

			reject();
		});
		*/
	});
}