import PDFDocument from 'pdfkit';
import * as fs from 'fs';
import * as s3bucketController from '../controllers/s3bucketController.js';

// Queries item details for view page, including it's history
export function item_view_get(req, res, next) {
	
	const sqlQuery = 'SELECT * FROM matter AS m \
										JOIN (SELECT ukey, udisplay FROM users) \
										AS u ON m.mtuser = u.ukey \
										JOIN (SELECT ukey AS asgkey, udisplay AS uassignee FROM users) \
										AS a ON m.mtassignee = a.asgkey \
										JOIN (SELECT ukey AS lastkey, udisplay AS ulastuser FROM users) \
										AS l ON m.mtlastuser = l.lastkey \
										WHERE mtkey = ' + req.params.id

	req.app.locals.pool.query(sqlQuery)
		.then((result) => {
			if (result.rows[0] == null) {
				res.status(400).json({
					"Error":"Item doesn't exist!"
				})
			} else {
				req.item = result.rows[0];
				return next();
			}
		})
		.catch((error) => {
			res.status(400).json({
				"Error":error.stack
			})
		})
};

// Queries just item details from matter table, because history is not editable
export function item_editview_get(req, res) {

	const sqlQuery = 'SELECT * FROM matter AS m \
										JOIN (SELECT ukey, udisplay FROM users) \
										AS u ON m.mtuser = u.ukey \
										JOIN (SELECT ukey AS asgkey, udisplay AS uassignee FROM users) \
										AS a ON m.mtassignee = a.asgkey \
										JOIN (SELECT ukey AS lastkey, udisplay AS ulastuser FROM users) \
										AS l ON m.mtlastuser = l.lastkey \
										WHERE mtkey = ' + req.params.id

	req.app.locals.pool.query(sqlQuery)
		.then((result) => {
			if (result.rows[0] == null) {
				res.status(400).json({
					"Error":"Item doesn't exist!"
				})
			} else {
				res.send(result.rows[0]);
			}
		})
		.catch((error) => {
			res.status(400).json({
				"Error":error.stack
			})
		})
};

// Updates item in matter table, then inserts to history table
export function item_submit_put(req, res) {

	const sqlQuery = {
		text: 'UPDATE matter \
					 SET mttitle = $1, mtassignee = $2, mtpriority = $3,  mtdeadline = $4, \
					  	 mtsections = $5, mtlastedited = now()::timestamp(0), mtlastuser = $6\
					 WHERE mtkey = $7',
		values: [req.body.mttitle, req.body.mtassignee, req.body.mtpriority.toUpperCase(),
						 req.body.mtdeadline, req.body.mtsections, req.body.mtlastuser,
						 req.params.id]
	}

	// Need generated mtlastedited timestamp for history table
	const sqlQuery2 = 'SELECT mtlastedited FROM matter WHERE mtcontract = \'' 
										+ req.body.mtcontract + '\'';

	req.app.locals.pool.query(sqlQuery)
		.then((result) => {
			if (result.rows == null) {
				res.send('error');
			} else {
 				res.send('Item Updated');

				req.app.locals.pool.query(sqlQuery2)
					.then((result2) => {

						req.body.mtkey = req.params.id;
						req.body.mtlastedited = result2.rows[0].mtlastedited;

						// Convert matter to pdf. {doc, filename, bucketDir} added to req
						create_pdf(req);

						// Upload pdf to s3 bucket. dataLoc, versionId added to req
						s3bucketController.upload_doc(req);
						// item_history_post() called in .upload_doc()
					})
					.catch((error) => {
						res.status(400).json({
							"Error":error.stack
						})
					})
			}
		})
		.catch((error) => {
			res.status(400).json({
					'Error':'Invalid inputs. Please try again.'
			})
		})
	
};

// Queries type table to get relevant sections for the template of an item
export function item_type_format_get(req, res) {

	const sqlQuery = {
			                text: 'SELECT tpsections FROM type \
			                			 WHERE tptype = $1 and tpsubtype = $2',
			                values: [req.params.itemtype.toLowerCase(), req.params.subtype]
            			 }

	req.app.locals.pool.query(sqlQuery)
		.then((result) => {
			if (result.rows[0] == null) {
				res.send('error');
			} else {
				res.send(result.rows[0]);
			}
		})
		.catch((error) => {
			res.status(400).json({
				"Error":error.stack
			})
		});
};

// Inserts/submits new matter
export function item_new_post(req, res) {

	// current user is mtlastuser
	req.body.mtlastuser = req.body.mtuser
	
	const sqlQuery = {
    text: 'INSERT INTO matter (mttype,mtsubtype,mtname,mttitle,mtcontract,' +
    													 'mtuser,mtassignee,mtpriority,mtdeadline,' +
    													 'mtsections,mtcreatedate,mtlastedited,mtlastuser)' +
    			 'VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,now()::timestamp(0),now()::timestamp(0),$11)',
    values: [req.body.mttype.toLowerCase(), req.body.mtsubtype, req.body.mtname,
    				 req.body.mttitle, req.body.mtcontract, req.body.mtuser, 
    				 parseInt(req.body.mtassignee), req.body.mtpriority.toUpperCase(), req.body.mtdeadline, 
    				 req.body.mtsections,req.body.mtlastuser]
 	}

 	// Need generated mtlastedited timestamp for history table
 	const sqlQuery2 = 'SELECT mtkey, mtlastedited FROM matter WHERE mtcontract = \'' 
										+ req.body.mtcontract + '\'';

  req.app.locals.pool.query(sqlQuery)
  	.then((result) => {
			if (result.rows == null) {
				res.send('error');
			} else {
				
				console.log('New Item Submitted to Matter Table')
 				res.send('Item History added');
				req.app.locals.pool.query(sqlQuery2)
					.then((result2) => {

						req.body.mtkey = result2.rows[0].mtkey;
						req.body.mtlastedited = result2.rows[0].mtlastedited;

						// Convert matter to pdf. {doc, filename, bucketDir} added to req
						create_pdf(req);

						// Upload pdf to s3 bucket. dataLoc, versionId added to req
						s3bucketController.upload_doc(req);
						// item_history_post() called in .upload_doc()
					})
					.catch((error) => {
						res.status(400).json({
								'Error':'Something went wrong with your input. Please try again.'
						})
					})

			}
		})
		.catch((error) => {
			res.status(400).json({
					'Error':'Something went wrong with your input. Please try again.'
			})
		})
};

// Queries history of an item
export function item_history_get(req, res) {

	let mtkey;
	if (req.params.id) {
		mtkey = req.params.id;
	} else {
		mtkey = req.item.mtkey;
	}

	const sqlQuery = 'SELECT * FROM history AS h \
										JOIN (SELECT ukey, udisplay AS ulastuser FROM users) \
										AS u ON h.hslastuser = u.ukey \
										WHERE hsmatter = ' + mtkey + ' \
										ORDER BY hskey DESC';

	req.app.locals.pool.query(sqlQuery)
		.then((result) => {
			if (result.rows == null) {
				res.send('error');
			} else {
				const data = {
					item: req.item,
					history: result.rows
				};
				res.send(data);
			}
		})
		.catch((error) => {
			res.status(400).json({
				"Error":error.stack
			})
		})

};

// Inserts new history
// req body: hsmatter (mtkey, or :id), hsuser (creator/mtuser), timestamp (mtlastedited), 
//        hslink and hsversion (from s3 upload), hslastuser (mtlastuser)
export function item_history_post(req, res) {
	
	const sqlQuery = {
    text: 'INSERT INTO history (hsmatter,hsuser,hstimestamp,hslink,hsversion,hslastuser) ' +
    			'VALUES ($1,$2,$3,$4,$5,$6)',
    values: [req.body.mtkey, req.body.mtuser, req.body.mtlastedited, req.body.dataLoc, 
    				 req.body.versionId, req.body.mtlastuser]
 	}

 	req.app.locals.pool.query(sqlQuery, (error, result) => {
 		if (error) {
 			res.status(400).json({
				"Error":error.stack
			})
 		} else {
 			res.send('Item History Added');
 		}
 	});

};

// Creates PDFkit instance 'doc' for PDF file
export function create_pdf(req, res, next) {
	// Getting json keys to display later
	let keys = Object.keys(req.body.mtsections);

	var doc = new PDFDocument();
	for(var col in keys){
		// console.log(keys[col])
		doc.text(`${keys[col]}`, {
			underline: true
		});

		let requestSection = req.body.mtsections[keys[col]]
		// console.log(`\t${keys[col]}: ${requestSection}`)
		doc.text(`${requestSection}`)
	}
	doc.end();

	req.body.doc = doc;
	//console.log('PDF Created');
}
