import AWS from 'aws-sdk';
import * as fs from 'fs';
import * as path from 'path';
import S3CONFIG from '../s3bucket-info.json';
import * as itemController from '../controllers/itemController.js';

// Uploads new or edited documents PDF form to S3 bucket, AWS version controlled
export function upload_doc(req, res) {

	// configure AWS environment for access
	AWS.config.update({
		accessKeyId: S3CONFIG.aKey,
		secretAccessKey: S3CONFIG.secretKey
	});

	const s3 = new AWS.S3();

	// directory on S3 bucket to upload to
	const bucketDir = req.body.mttype;
	const filename = req.body.mtname;
	const body = req.body.doc;

	// configure parameters for bucket to upload to
	const bucketParams = {
		Bucket: S3CONFIG.bucketName,
		Body: body,
		Key: bucketDir+"/"+filename+".pdf",
		ContentType : 'application/pdf'
	};


	// uploads file from /data directory to s3 bucket
	s3.upload(bucketParams, function(err, data) {
		//handle error
		if (err) {
			//console.log("Error: Upload to S3 failed", err);
			res.json({sucess: false, error: err});
		}
		//success
		if (data) {
			//console.log("Uploaded to S3:", data.Location);

			req.body.dataLoc = data.Location;
			req.body.versionId = data.VersionId;

			// Calls function to insert new history with s3 info
			itemController.item_history_post(req);
			
			//res.json({sucess: true, dataLoc: data.Location, versionId: data.VersionId});
		}
	});

};

// Download version specified document file from S3 bucket
// route is /item/:id/download/:versionId
// req = {filename, bucketDir}, result is document opened in browser
export function download_doc(req, res) {
	// configure AWS environment for access
	AWS.config.update({
		accessKeyId: S3CONFIG.aKey,
		secretAccessKey: S3CONFIG.secretKey
	});

	const s3 = new AWS.S3();

	const matterKey = req.params.id;
	// version id of selected document version
	const versionId = req.params.versionId;
	// directory of S3 bucket to download from
	const directory = req.body.bucketDir+"/"+req.body.filename+".pdf";

	// configure parameters for bucket to download from
	const bucketParams = {
		Bucket: S3CONFIG.bucketName,
		Key: directory,
		VersionId: versionId
	};

	// retrieves object from s3 bucket and results in the browser
	s3.getSignedUrl('getObject', bucketParams, (err, data) => {
	    if (err) {
	      console.log("Error: Download failed", err);
	      res.status(500).json({error:"error" + err});
	    }
	    const returnData = {
	        signedRequest: data,
	    };
	    res.send(JSON.stringify(returnData));
	  });

};
