// const axios = require("axios");
// const { splitSite } = require("../middlewares");
// const db = require("../models");
// const DocTemplate = db.doctemplate
// var multer = require('multer');
// var PizZip = require('pizzip');
// var Docxtemplater = require('docxtemplater');
// var fs = require('fs');
// const path = require('path');
// // const docxConverter = require('docx-pdf');
// var libre = require('libreoffice-convert');


// exports.createPDFFromDocTemplateName = (req, res) => {
//     console.log('what', __dirname.replace('/controllers', ''));
// 	var inputData = req.query.inputData;
// 	var docTemplateName = req.query.docTemplateName;
// 	// var transportationId = req.body.transportationId;d
// 	// var transportationName = req.body.transportationName;
// 	DocTemplate.find({name: docTemplateName}).then((data) => {
// 		try {
// 			if (data && data.length > 0) {
// 				var docTemplate = data[0] || {};
// 				var templateDoc = `${__dirname.replace('/controllers', '')}${docTemplate?.file[0]?.url}`;
// 				var outputFileRandom = Math.ceil(Math.random() * 100000000);
// 				var outputFile = `/tmp/${docTemplate.name}_${outputFileRandom}.docx`;
// 				var content = fs.readFileSync(templateDoc, 'binary');
// 				var zip = new PizZip(content);
// 				var doc = new Docxtemplater(zip, {
// 				    paragraphLoop: true,
//             linebreaks: true,
// 				});
				
				

// 				try {
// 					// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
// 					doc.render(JSON.parse(inputData));
// 				} catch (error) {
// 					// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
// 					function replaceErrors(key, value) {
// 						if (value instanceof Error) {
// 							return Object.getOwnPropertyNames(value).reduce(function(error, key) {
// 								error[key] = value[key];
// 								return error;
// 							}, {});
// 						}
// 						return value;
// 					}
// 					console.log(JSON.stringify({error: error}, replaceErrors));
// 					if (error.properties && error.properties.errors instanceof Array) {
// 						const errorMessages = error.properties.errors.map(function (error) {
// 							return error.properties.explanation;
// 						}).join("\n");
// 						console.log('errorMessages', errorMessages);
// 						// errorMessages is a humanly readable message looking like this :
// 						// 'The tag beginning with "foobar" is unopened'
// 					}
// 					// callback && callback(error, null, { message:'error in creating doc from template' });
// 				}
// 				// save doc to output file
// 				var buf = doc.getZip().generate({type: 'nodebuffer'});
// 				// buf is a nodejs buffer, you can either write it to a file or do anything else with it.
// 				fs.writeFileSync(outputFile, buf);
// 				var outputFilename = outputFile || {};
// 				var outputPdfPath = outputFilename.substr(0, outputFilename.length - 5) + '.pdf';
// 				console.log('outputPDF:', outputPdfPath);
// 				var extend = 'pdf';
// 				// Read file
// 				// var outputFilename = outputFile || {};
// 				// console.log('filename', `/tmp/${docTemplate.name}_${outputFileRandom}.docx`)
// 				// docxConverter(path.resolve(`/tmp/${docTemplate.name}_${outputFileRandom}.docx`), path.resolve(`/tmp/${docTemplate.name}_${outputFileRandom}.pdf`), (err, result) => {
// 				// 	if (err) console.log(err);
// 				// 	else {
// 				// 	    console.log('res', res);
// 				// 	    res.download(result, (error) => {
//     // 						console.log('Download PDF error')
//     // 					})
// 				// 	}
// 				// });
			
// 				var infile = fs.readFileSync(outputFile);
// 				// Convert it to pdf format with undefined filter (see Libreoffice doc about filter)
// 				try {
// 					libre.convert(infile, extend, undefined, (err, done) => {
// 						if (err) {
// 							console.log('Error converting file:', err);
// 						}
// 						// Here in done you have pdf file which you can save or transfer in another stream
// 						fs.writeFileSync(outputPdfPath, done);
// 						console.log('Conver docx to pdf, Done.');
// 						res.download(outputPdfPath, function(error) {
// 							if (error) {
// 								console.log('Error in sending download file ${outputPdfPath}');
// 							}
// 						});
// 					});
// 				} catch (e) {
// 					console.log(e);
// 				}
				
// 			} else {
// 				res.status(404).send({
// 					success: false,
// 					message: "Docs Template doesn't exist"
// 				})
// 			}
// 		} catch(e) {
// 			console.log(e);
// 		}
// 	}).catch(err => {
// 		res.status(500).send({
// 			success: false,
// 			message: "Error Geting docs"
// 		});
// 	});
// }

// exports.createDocFromDocTemplateName = (req, res) => {
// 	console.log('what', __dirname.replace('/controllers', ''));
// 	// var inputData = req.query.inputData;
// 	var inputData = req.body.inputData;
// 	var docTemplateName = req.body.docTemplateName;
// 	DocTemplate.find({name: docTemplateName}).then((data) => {
// 	    console.log(data);
// 		try {
// 			if (data && data.length > 0) {
// 				var docTemplate = data[0] || {};
// 				var templateDoc = `${__dirname.replace('/controllers', '')}${docTemplate?.file[0]?.url}`;
// 				var outputFileRandom = Math.ceil(Math.random() * 100000000);
// 				var outputFile = `/tmp/${docTemplate.name}_${outputFileRandom}.docx`;
// 				var content = fs.readFileSync(templateDoc, 'binary');
// 				var zip = new PizZip(content);
// 				var doc = new Docxtemplater(zip, {
// 						paragraphLoop: true,
// 						linebreaks: true,
// 				});

// 				try {
// 					// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
// 					doc.render(JSON.parse(inputData));
// 				} catch (error) {
// 					// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
// 					function replaceErrors(key, value) {
// 						if (value instanceof Error) {
// 							return Object.getOwnPropertyNames(value).reduce(function(error, key) {
// 								error[key] = value[key];
// 								return error;
// 							}, {});
// 						}
// 						return value;
// 					}
// 					console.log(JSON.stringify({error: error}, replaceErrors));
// 					if (error.properties && error.properties.errors instanceof Array) {
// 						const errorMessages = error.properties.errors.map(function (error) {
// 							return error.properties.explanation;
// 						}).join("\n");
// 						console.log('errorMessages', errorMessages);
// 						// errorMessages is a humanly readable message looking like this :
// 						// 'The tag beginning with "foobar" is unopened'
// 					}
// 					// callback && callback(error, null, { message:'error in creating doc from template' });
// 				}
// 				// save doc to output file
// 				var buf = doc.getZip().generate({type: 'nodebuffer'});
// 				// buf is a nodejs buffer, you can either write it to a file or do anything else with it.
// 				fs.writeFileSync(outputFile, buf);
// 				var outputFilename = outputFile || {};
				
// 				res.send(outputFilename, (error) => {
// 					if (error) {
// 						console.log('Error in downloading excel')
// 					}
// 				});

// 				console.log('Doc Download Completes')
				
// 			} else {
// 				res.status(404).send({
// 					success: false,
// 					message: "Docs Template doesn't exist"
// 				})
// 			}
// 		} catch(e) {
// 			console.log(e);
// 		}
// 	}).catch(err => {
// 		res.status(500).send({
// 			success: false,
// 			message: "Error Geting docs"
// 		});
// 	});
// 	// ids.forEach(id => {
// 	// 	CalendarEvent.findByIdAndUpdate(id, {link_event_uuid: transportationId,
// 	// 		link_event_name: transportationName}, { useFindAndModify: false })
// 	//   .then(data => {
// 	//     if (!data) {
// 	//       res.status(404).send({
// 	//         message: `Cannot update Event with id=${id}. Maybe Event was not found!`
// 	//       });
// 	//     } else res.send({ success: true, message: "Event was updated successfully." });
// 	//   })
// 	//   .catch(err => {
// 	//     res.status(500).send({
// 	//       success: false,
// 	//       message: "Error updating Event with id=" + id
// 	//     });
// 	//   });
// 	// }) 
// }



const axios = require("axios");
const { splitSite } = require("../middlewares");
const db = require("../models");
const DocTemplate = db.doctemplate;
const Event = db.calendar_event;
var multer = require('multer');
var PizZip = require('pizzip');
var Docxtemplater = require('docxtemplater');
var fs = require('fs');
const path = require('path');
// const docxConverter = require('docx-pdf');
var libre = require('libreoffice-convert');
const moment = require("moment-timezone");
const BASE_UPLOAD_DIR = "/www/wwwroot/upload/";

const resolveTemplateFilePath = (fileUrl = "") => {
  if (!fileUrl) return "";
  if (fileUrl.startsWith("/files/")) {
    return fileUrl.replace("/files/", BASE_UPLOAD_DIR);
  }
  return `${__dirname.replace("/controllers", "")}${fileUrl}`;
};


exports.createPDFFromDocTemplateName = (req, res) => {
  console.log('what', __dirname.replace('/controllers', ''));
	var inputData = JSON.parse(req.query.inputData);
	var docTemplateName = req.query.docTemplateName;
  const site = splitSite.findSiteNumber(req);
	const eventIds =inputData?.eventIds;
	Event.find({ '_id': { $in: eventIds } }).then((events) => {
		const docData = {
			events: []
		};
		events.forEach((event) => {
			docData.events.push({
				event_time: moment(event.start_time).format('hh:mm A MM/DD/YYYY dddd'),
				client_name: event.data.client_name || '',
				client_status: '会员',
				//client_dob: event.data.client_birth_date || '',
				//client_pcp: event.data.client_pcp || '',
				//client_pharmacy: event.data.client_pharmacy || '',
				client_seating: event.data.client_seating || '',
				doctor_name: event.data.resource_name || '',
				//doctor_phone: event.data.resource_phone || '',
				doctor_contact: event.data.resource_contact || '',
				doctor_address: event.data.resource_address || '',
				//title: event.title || '',
				description: event.description || '',
				interpreter: event.data.interpreter || '',
				//fasting: event.data.fasting || '',
				//confirmed: event.data.confirmed,
				//new_patient: event.data.new_patient,
				//doc_order: event.data.doc_order,
				//need_id: event.data.need_id,
				//need_med_list: event.data.need_med_list,
				reason: event.data.reason || '',
				other: event.data.other || ''
			});
		});
		// var transportationId = req.body.transportationId;d
		// var transportationName = req.body.transportationName;
		DocTemplate.findOne({
      name: docTemplateName,
      site,
      "file.0": { $exists: true }
    }).sort({ edit_date: -1, updatedAt: -1, createdAt: -1 }).then((docTemplate) => {
			try {
				if (docTemplate) {
					var templateDoc = resolveTemplateFilePath(docTemplate?.file?.[0]?.url);
          if (!templateDoc || !fs.existsSync(templateDoc)) {
            return res.status(404).send({
              success: false,
              message: "Doc template file not found on server"
            });
          }
					var outputFileRandom = Math.ceil(Math.random() * 100000000);
					var outputFile = `/tmp/${docTemplate.name}_${outputFileRandom}.docx`;
					var content = fs.readFileSync(templateDoc, 'binary');
					var zip = new PizZip(content);
					var doc = new Docxtemplater(zip, {
							paragraphLoop: true,
							linebreaks: true,
					});
					
					try {
						// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
						doc.render(docData);
					} catch (error) {
						// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
						function replaceErrors(key, value) {
							if (value instanceof Error) {
								return Object.getOwnPropertyNames(value).reduce(function(error, key) {
									error[key] = value[key];
									return error;
								}, {});
							}
							return value;
						}
						console.log(JSON.stringify({error: error}, replaceErrors));
						if (error.properties && error.properties.errors instanceof Array) {
							const errorMessages = error.properties.errors.map(function (error) {
								return error.properties.explanation;
							}).join("\n");
							console.log('errorMessages', errorMessages);
							// errorMessages is a humanly readable message looking like this :
							// 'The tag beginning with "foobar" is unopened'
						}
						// callback && callback(error, null, { message:'error in creating doc from template' });
					}
					// save doc to output file
					var buf = doc.getZip().generate({type: 'nodebuffer'});
					// buf is a nodejs buffer, you can either write it to a file or do anything else with it.
					fs.writeFileSync(outputFile, buf);
					var outputFilename = outputFile || {};
					var outputPdfPath = outputFilename.substr(0, outputFilename.length - 5) + '.pdf';
					console.log('outputPDF:', outputPdfPath);
					var extend = 'pdf';
					// Read file
					// var outputFilename = outputFile || {};
					// console.log('filename', `/tmp/${docTemplate.name}_${outputFileRandom}.docx`)
					// docxConverter(path.resolve(`/tmp/${docTemplate.name}_${outputFileRandom}.docx`), path.resolve(`/tmp/${docTemplate.name}_${outputFileRandom}.pdf`), (err, result) => {
					// 	if (err) console.log(err);
					// 	else {
					// 	    console.log('res', res);
					// 	    res.download(result, (error) => {
			// 						console.log('Download PDF error')
			// 					})
					// 	}
					// });
				
					var infile = fs.readFileSync(outputFile);
					// Convert it to pdf format with undefined filter (see Libreoffice doc about filter)
					try {
						libre.convert(infile, extend, undefined, (err, done) => {
							if (err) {
								console.log('Error converting file:', err);
								return res.status(500).send({
									success: false,
									message: "Error converting doc file to PDF"
								});
							}
							// Here in done you have pdf file which you can save or transfer in another stream
							fs.writeFileSync(outputPdfPath, done);
							console.log('Conver docx to pdf, Done.');
							res.download(outputPdfPath, function(error) {
								if (error) {
									console.log('Error in sending download file ${outputPdfPath}');
									return res.status(500).send({
										success: false,
										message: "Error downloading generated PDF"
									});
								}
							});
						});
					} catch (e) {
						console.log(e);
						return res.status(500).send({
							success: false,
							message: "Error generating PDF from doc template"
						});
					}
					
				} else {
					res.status(404).send({
						success: false,
						message: "Docs Template doesn't exist for this site, or file not uploaded yet"
					})
				}
			} catch(e) {
				console.log(e);
				return res.status(500).send({
					success: false,
					message: "Error processing doc template"
				});
			}
		}).catch(err => {
			res.status(500).send({
				success: false,
				message: "Error Geting docs"
			});
		});
	})
}

exports.createDocFromDocTemplateName = (req, res) => {
	console.log('what', __dirname.replace('/controllers', ''));
	var inputData = JSON.parse(req.query.inputData);
	const eventIds = inputData?.eventIds;
	var docTemplateName = req.query.docTemplateName;
  const site = splitSite.findSiteNumber(req);
	Event.find({ '_id': { $in: eventIds } }).then((events) => {
		const docData = {
			events: []
		};
		events.forEach((event) => {
			docData.events.push({
				event_time: moment(event.start_time).format('hh:mm A MM/DD/YYYY dddd'),
				client_name: event.data.client_name || '',
				client_status: '会员',
				//client_dob: event.data.client_birth_date || '',
				//client_pcp: event.data.client_pcp || '',
				//client_pharmacy: event.data.client_pharmacy || '',
				client_seating: event.data.client_seating || '',
				doctor_name: event.data.resource_name || '',
				//doctor_phone: event.data.resource_phone || '',
				doctor_contact: event.data.resource_contact || '',
				doctor_address: event.data.resource_address || '',
				//title: event.title || '',
				description: event.description || '',
				interpreter: event.data.interpreter || '',
				//fasting: event.data.fasting || '',
				//confirmed: event.data.confirmed,
				//new_patient: event.data.new_patient,
				//doc_order: event.data.doc_order,
				//need_id: event.data.need_id,
				//need_med_list: event.data.need_med_list,
				reason: event.data.reason || '',
				other: event.data.other || ''
			});
		});

		DocTemplate.findOne({
      name: docTemplateName,
      site,
      "file.0": { $exists: true }
    }).sort({ edit_date: -1, updatedAt: -1, createdAt: -1 }).then((docTemplate) => {
			try {
				if (docTemplate) {
					var templateDoc = resolveTemplateFilePath(docTemplate?.file?.[0]?.url);
          if (!templateDoc || !fs.existsSync(templateDoc)) {
            return res.status(404).send({
              success: false,
              message: "Doc template file not found on server"
            });
          }
					var outputFileRandom = Math.ceil(Math.random() * 100000000);
					var outputFile = `/tmp/${docTemplate.name}_${outputFileRandom}.docx`;
					var content = fs.readFileSync(templateDoc, 'binary');
					var zip = new PizZip(content);
					var doc = new Docxtemplater(zip, {
							paragraphLoop: true,
							linebreaks: true,
					});

					try {
						// render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
						doc.render(docData);
					} catch (error) {
						// The error thrown here contains additional information when logged with JSON.stringify (it contains a properties object containing all suberrors).
						function replaceErrors(key, value) {
							if (value instanceof Error) {
								return Object.getOwnPropertyNames(value).reduce(function(error, key) {
									error[key] = value[key];
									return error;
								}, {});
							}
							return value;
						}
						console.log(JSON.stringify({error: error}, replaceErrors));
						if (error.properties && error.properties.errors instanceof Array) {
							const errorMessages = error.properties.errors.map(function (error) {
								return error.properties.explanation;
							}).join("\n");
							console.log('errorMessages', errorMessages);
							// errorMessages is a humanly readable message looking like this :
							// 'The tag beginning with "foobar" is unopened'
						}
						// callback && callback(error, null, { message:'error in creating doc from template' });
					}
					// save doc to output file
					var buf = doc.getZip().generate({type: 'nodebuffer'});
					// buf is a nodejs buffer, you can either write it to a file or do anything else with it.
					fs.writeFileSync(outputFile, buf);
					var outputFilename = outputFile || {};
					
					res.download(outputFilename, (error) => {
						if (error) {
							console.log('Error in downloading excel')
							return res.status(500).send({
								success: false,
								message: "Error downloading generated doc file"
							});
						}
					});

					console.log('Doc Download Completes')
					
				} else {
					res.status(404).send({
						success: false,
						message: "Docs Template doesn't exist for this site, or file not uploaded yet"
					})
				}
			} catch(e) {
				console.log(e);
				return res.status(500).send({
					success: false,
					message: "Error processing doc template"
				});
			}
		}).catch(err => {
			res.status(500).send({
				success: false,
				message: "Error Geting docs"
			});
		});
	});
}

