// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import axios from 'axios';
import { Cookies } from 'react-cookie';
import cookie from 'cookie';
import moment from 'moment';
import jwt from 'jsonwebtoken';
import { cors } from '../../../lib/cors';
import { inspect } from 'util';
import fs from 'fs';
import { PDFDocument, rgb } from 'pdf-lib';
import fontkit from '@pdf-lib/fontkit';

const address = {
	100000000: "legal", 
	100000001: "fact", 
	100000002: "postal", 
};

const personal_doctypes = {
	100000000: "Паспорт РФ", 
	100000001: "Иностранный паспорт", 
	100000002: "Вид на жительство", 
};

const fields = {
	main: {
		title: { name: "main_title", type: "text", bind: null, }, 
		inn: { name: "main_inn", type: "text", bind: null, }, 
		kpp: { name: "main_kpp", type: "text", bind: null, }, 
		email: { name: "main_email", type: "text", bind: null, }, 
		telephone: { name: "main_telephone", type: "text", bind: null, }, 
		websiteurl: { name: "main_website", type: "text", bind: null, }, 
		financial_loan: { name: "main_financial_loan", type: "text", bind: null, }, 

		individual_executive_oop: { name: "ruler_title", type: "text", bind: null }, 
		individual_executive_inn: { name: "ruler_inn", type: "text", bind: null }, 
		individual_executive_kpp: { name: "ruler_kpp", type: "text", bind: null }, 
		individual_executive_docnum: { name: "ruler_docnum", type: "text", bind: null }, 
		individual_executive_docdate: { name: "ruler_docdate", type: "text", bind: null, date: true }, 

		high_level: { name: "execution_high", type: "text", bind: null, size: 6 }, 
		board_of_directors: { name: "execution_counsil", type: "text", bind: null, size: 6 }, 
		collective_executive: { name: "execution_team", type: "text", bind: null, size: 6 }, 
		individual_executive: { name: "execution_sole", type: "text", bind: null, size: 6 }, 
		other_control: { name: "execution_another", type: "text", bind: null, size: 6 }, 
		mail_delivery_address_type: { name: "address_type", type: "radio", bind: null }, 
	}, 
	contacts: {
		fact_address: { name: "address_fact", type: "text", bind: null }, 
		postal_address: { name: "address_postal", type: "text", bind: null }, 
	}, 
	head_person: {
		fullname: { name: "head_fullname", type: "text", bind: null }, 
		jobtitle: { name: "head_jobtitle", type: "text", bind: null }, 
		/*
		Запрос 2024-02-08 на удаление даты назначения и даты окончания полномочий

		assignment_date: { name: "head_date", type: "text", bind: null, date: true }, 
		credentials_dateend: { name: "head_dateend", type: "text", bind: null, date: true }, 
		indefinite: { name: "head_date_infinite", type: "checkbox", bind: null }, 
		*/
		telephone: { name: "head_phone", type: "text", bind: null }, 
		email: { name: "head_email", type: "text", bind: null }, 
	}, 
	signatory_person: {
		fullname: { name: "signer_fullname", type: "text", bind: null }, 
		jobtitle: { name: "signer_jobtitle", type: "text", bind: null }, 
		signer_rule_basic: { name: "signer_reason", type: "text", bind: null }, 
		docdate: { name: "signer_docdate", type: "text", bind: null, date: true }, 
		docnumber: { name: "signer_docnum", type: "text", bind: null }, 
		telephone: { name: "signer_phone", type: "text", bind: null }, 
		email: { name: "signer_email", type: "text", bind: null }, 
	}, 
	founder_persons: 
	[
		{
			fullname: { name: "shareholder_1_fullname", type: "text", bind: null, size: 6 }, 
			personal: { name: "shareholder_1_personal", type: "text", bind: null, size: 6 }, 
			registration: { name: "shareholder_1_registration", type: "text", bind: null, size: 6 }, 
			founder_part: { name: "shareholder_1_part", type: "text", bind: null, size: 6 }, 
			is_beneficial: { name: "shareholder_1_ben", type: "radio", bind: null }, 
		}, 
		{
			fullname: { name: "shareholder_2_fullname", type: "text", bind: null, size: 6 }, 
			personal: { name: "shareholder_2_personal", type: "text", bind: null, size: 6 }, 
			registration: { name: "shareholder_2_registration", type: "text", bind: null, size: 6 }, 
			founder_part: { name: "shareholder_2_part", type: "text", bind: null, size: 6 }, 
			is_beneficial: { name: "shareholder_2_ben", type: "radio", bind: null, size: 6 }, 
		}, 
		{
			fullname: { name: "shareholder_3_fullname", type: "text", bind: null, size: 6 }, 
			personal: { name: "shareholder_3_personal", type: "text", bind: null, size: 6 }, 
			registration: { name: "shareholder_3_registration", type: "text", bind: null, size: 6 }, 
			founder_part: { name: "shareholder_3_part", type: "text", bind: null, size: 6 }, 
			is_beneficial: { name: "shareholder_3_ben", type: "radio", bind: null }, 
		}, 
		{
			fullname: { name: "shareholder_4_fullname", type: "text", bind: null, size: 6 }, 
			personal: { name: "shareholder_4_personal", type: "text", bind: null, size: 6 }, 
			registration: { name: "shareholder_4_registration", type: "text", bind: null, size: 6 }, 
			founder_part: { name: "shareholder_4_part", type: "text", bind: null, size: 6 }, 
			is_beneficial: { name: "shareholder_4_ben", type: "radio", bind: null }, 
		}, 
	], 
	non_profit: {
		fin_source_business: { name: "nko_revenue", type: "checkbox", bind: null }, 
		fin_source_donate: { name: "nko_donation", type: "checkbox", bind: null }, 
		fin_source_fees: { name: "nko_members", type: "checkbox", bind: null }, 
		fin_source_another: { name: "nko_another", type: "checkbox", bind: null }, 
		fin_source_another_description: { name: "nko_another_description", type: "text", bind: null, size: 6 }, 
		foreign_payers: { name: "external", type: "radio", bind: null }, 
		fin_goals_cars: { name: "nko_object_cars", type: "text", bind: null, size: 6 }, 
		fin_goals_trucks: { name: "nko_object_trucks", type: "text", bind: null, size: 6 }, 
		fin_goals_special: { name: "nko_object_special", type: "text", bind: null, size: 6 }, 
	}, 
	licenses: { name: "licenses", type: "text", bind: null, size: 5 }, 
};

function good(value)
{
	if(value !== undefined && value !== null && value !== "")
	{
		return true;
	}

	return false;
}

export default async function handler(req, res) 
{
	console.log("API", "questionnaire", "get");
	console.log(req.body);
	console.log("-".repeat(50));
	const { questionnaire, filename, base64 } = req.body;

	console.log("API", "questionnaire", "get", { questionnaire });

	await cors(req, res);

	if(req.headers.cookie !== undefined)
	{
		const cookies = cookie.parse(req.headers?.cookie ? req.headers?.cookie : "");

		if(cookies.jwt !== undefined && cookies.jwt !== null)
		{
			var client_jwt_decoded = jwt.verify(cookies.jwt, process.env.JWT_SECRET_CLIENT);
			var crm_jwt = jwt.sign({ acc_number: client_jwt_decoded.acc_number }, process.env.JWT_SECRET_CRM, { noTimestamp: true });

			console.log("API", "download", "__dirname", __dirname);
			const formPdfBytes = fs.readFileSync(`${ __dirname }/../../../../../lib/evo_anketa_v2_empty_licenses_20240503.pdf`);
			const fontBytes = fs.readFileSync(`${ __dirname }/../../../../../lib/ubuntu_mono_regular.ttf`);

			const pdfDoc = await PDFDocument.load(formPdfBytes);
			pdfDoc.registerFontkit(fontkit);
			const formFont = await pdfDoc.embedFont(fontBytes);

			const form = pdfDoc.getForm();

			for(let group in fields)
			{
				if(group === "licenses")
				{
					//fields[group].bind = form.getTextField(fields[group].name);
					//if(fields[group].size !== undefined) { fields[group].bind.setFontSize(fields[group].size); }
					//fields[group].bind.setText(`${ questionnaire[group] }`);

					const page = pdfDoc.getPage(1);
					page.drawRectangle({
						x: 150,
						y: 174,
						width: 412,
						height: 26,
						color: rgb(0.87, 0.87, 0.87),
					});

					if(questionnaire[group] !== null)
					{
						let licenses = questionnaire[group];
						if(typeof licenses !== "string")
						{
							licenses = licenses.join(", ");
						}

						page.drawText(licenses, {
							x: 152,
							y: licenses.length > 500 ? 195 : (licenses.length > 400) ? 195 : 193,
							size: licenses.length > 500 ? 4 : (licenses.length > 400) ? 5 : 6,
							font: formFont,
							color: rgb(0, 0, 0),
							maxWidth: 412, 
							lineHeight: licenses.length > 500 ? 4 : (licenses.length > 400) ? 5 : 6, 
						});
					}
				}
				else if(group === "founder_persons")
				{
					for(let p in questionnaire[group])
					{
						for(let field in fields[group][p])
						{
							if(field === "fullname")
							{
								fields[group][p][field].bind = form.getTextField(fields[group][p][field].name);
								if(fields[group][p][field].size !== undefined) { fields[group][p][field].bind.setFontSize(fields[group][p][field].size); }
								fields[group][p][field].bind.setText(`${ questionnaire[group][p].lastname.toUpperCase() } ${ questionnaire[group][p].firstname.toUpperCase() }${ good(questionnaire[group][p].middlename) ? ` ${ questionnaire[group][p].middlename.toUpperCase() }` : "" }`);
							}
							else if(field === "personal")
							{
								const { birthdate, } = questionnaire[group][p];
								const { placebirth, citizenship, doctype, seria, docnumber, code, issueby, issuedate, } = questionnaire[group][p].identity_document;
								fields[group][p][field].bind = form.getTextField(fields[group][p][field].name);
								if(fields[group][p][field].size !== undefined) { fields[group][p][field].bind.setFontSize(fields[group][p][field].size); }
								fields[group][p][field].bind.setText(`${ moment(birthdate).format("DD.MM.YYYY") }, ${ placebirth }, ${ citizenship.title }, ${ personal_doctypes[doctype].toString().toUpperCase() } ${ seria.toString() } ${ docnumber.toString() }, выдан ${ issueby.toString() }, ${ moment(issuedate).format("DD.MM.YYYY") }${ code !== undefined && code !== null ? ", " + code.toString() : "" }`.toUpperCase());
							}
							else if(field === "registration")
							{
								const { registration_address, } = questionnaire[group][p].identity_document;
								if(good(registration_address.name))
								{
									let field_text_value = registration_address.name.toString().toUpperCase();
									/*
									let field_text_value = "";
									for(let a = 0; a < 7; a++)
									{
										for(let b = 0; b < 10; b++)
										{
											field_text_value = field_text_value + b;
											if(b === 5)
											{
												field_text_value = field_text_value + " ";
											}
										}
									}
									*/
									//const rx = new RegExp(/(\S)-(\S)/gim);
									//field_text_value = field_text_value.replace(rx, "$1- $2");

									fields[group][p][field].bind = form.getTextField(fields[group][p][field].name);
									console.log(`${ group }_${ p }_${ field }`, { is_scrollable: fields[group][p][field].bind.isScrollable() });

									if(fields[group][p][field].size !== undefined) { fields[group][p][field].bind.setFontSize(fields[group][p][field].size); }

									/*
									if(field_text_value.length < 70)
									{
									}
									else if(field_text_value.length < 14)
									{
									}
									*/

									fields[group][p][field].bind.setText(field_text_value);
								}
							}
							else
							{
								if(fields[group][p][field].type === "checkbox")
								{
									if(questionnaire[group][p][field])
									{
										fields[group][p][field].bind = form.getCheckBox(fields[group][p][field].name);
										fields[group][p][field].bind.check();
									}
								}
								else if(fields[group][p][field].type === "radio")
								{
									if(questionnaire[group][p][field] !== undefined)
									{
										fields[group][p][field].bind = form.getRadioGroup(fields[group][p][field].name);
										let options = fields[group][p][field].bind.getOptions();

										if(questionnaire[group][p][field])
										{
											fields[group][p][field].bind.select("yes");
										}
										else
										{
											fields[group][p][field].bind.select("no");
										}
									}
								}
								else
								{
									if(good(questionnaire[group][p][field]))
									{
										fields[group][p][field].bind = form.getTextField(fields[group][p][field].name);
										if(fields[group][p][field].size !== undefined) { fields[group][p][field].bind.setFontSize(fields[group][p][field].size); }
										fields[group][p][field].bind.setText(questionnaire[group][p][field].toString());
									}
								}
							}
						}
					}
					continue;
				}
				else
				{
					if(group === "signatory_person" && !questionnaire[group].not_head_person) { continue; }

					for(let field in fields[group])
					{
						if(group === "main")
						{
							if(!questionnaire.signatory_person.delegation_agreement)
							{
								const r = ["individual_executive_oop", "individual_executive_inn", "individual_executive_kpp", "individual_executive_docnum", "individual_executive_docdate"];
								if(r.indexOf(field) > -1) { continue; }
							}
						}

						/*
						Запрос 2024-02-08 на удаление даты назначения и даты окончания полномочий

						if(group === "head_person")
						{
							if(field === "credentials_dateend")
							{
								if(questionnaire[group].indefinite)
								{
									continue;
								}
							}
						}
						*/

						if(group === "head_person")
						{
							if(field === "assignment_date" || field === "credentials_dateend" || field === "indefinite")
							{
								continue;
							}
						}

						if(field === "fullname")
						{
							fields[group][field].bind = form.getTextField(fields[group][field].name);
							if(fields[group][field].size !== undefined) { fields[group][field].bind.setFontSize(fields[group][field].size); }
							fields[group][field].bind.setText(`${ questionnaire[group].lastname.toUpperCase() } ${ questionnaire[group].firstname.toUpperCase() }${ good(questionnaire[group].middlename) ? ` ${ questionnaire[group].middlename.toUpperCase() }` : "" }`);
						}
						else if(field === "postal_address")
						{
							if(good(questionnaire[group].postal_address.name))
							{
								fields[group][field].bind = form.getTextField(fields[group][field].name);
								if(fields[group][field].size !== undefined) { fields[group][field].bind.setFontSize(fields[group][field].size); }
								fields[group][field].bind.setText(questionnaire[group].postal_address.name.toUpperCase());
							}
						}
						else if(field === "fact_address")
						{
							if(good(questionnaire[group].fact_address.name))
							{
								fields[group][field].bind = form.getTextField(fields[group][field].name);
								if(fields[group][field].size !== undefined) { fields[group][field].bind.setFontSize(fields[group][field].size); }
								fields[group][field].bind.setText(questionnaire[group].fact_address.name.toUpperCase());
							}
						}
						else if(field === "mail_delivery_address_type")
						{
							fields[group][field].bind = form.getRadioGroup(fields[group][field].name);
							fields[group][field].bind.select(address[ questionnaire[group].mail_delivery_address_type ]);
						}
						/*
						else if(field === "foreign_payers")
						{
							pdf_params[fields[group][field]] = questionnaire[group].foreign_payers ? 0 : 1;
						}
						*/
						else
						{
							if(fields[group][field].type === "checkbox")
							{
								if(questionnaire[group][field])
								{
									fields[group][field].bind = form.getCheckBox(fields[group][field].name);
									fields[group][field].bind.check();
								}
							}
							else if(fields[group][field].type === "radio")
							{
								if(questionnaire[group][field] !== undefined)
								{
									fields[group][field].bind = form.getRadioGroup(fields[group][field].name);
									
									if(questionnaire[group][field])
									{
										fields[group][field].bind.select("yes");
									}
									else
									{
										fields[group][field].bind.select("no");
									}
								}
							}
							else
							{
								if(good(questionnaire[group][field]))
								{
									fields[group][field].bind = form.getTextField(fields[group][field].name);
									if(fields[group][field].size !== undefined) { fields[group][field].bind.setFontSize(fields[group][field].size); }
									if(fields[group][field].date)
									{
										fields[group][field].bind.setText(moment(questionnaire[group][field]).format("DD.MM.YYYY"));
									}
									else
									{
										fields[group][field].bind.setText(questionnaire[group][field].toString().toUpperCase());
									}
								}
							}
						}
					}	
				}
			}

			form.updateFieldAppearances(formFont);
			form.flatten();

			if(!questionnaire.main.nko)
			{
				pdfDoc.removePage(2);
			}

			const pdfBytes = await pdfDoc.save();
			//responseType: 'blob', 
			fs.writeFileSync(`${ __dirname }/../../../../../uploads/${ client_jwt_decoded.acc_number }_questionnaire.pdf`, pdfBytes);
			//res.setHeader('Content-Type', 'application/pdf');
			//res.send(pdfBytes);
			console.log("pdfBytes.size", pdfBytes, pdfBytes.byteLength);
			if(base64)
			{
				//, 'binary'
				res.status(200).send(Buffer.from(pdfBytes).toString('base64'));
			}
			else
			{
				res.setHeader("filename", filename);
				res.setHeader('Content-Type', 'application/pdf');	
				res.status(200).send(Buffer.from(pdfBytes));
			}
			//res.setHeader('Content-Type', 'application/pdf');
			//res.status(200).send(pdfBytes);
		}
		else
		{
			res.status(403).send();
		}
	}
}