let express = require('express')

var multer  = require('multer')
var upload = multer({ dest: '../staticFiles/' }) //@TODO make this a global value
let router = express.Router()

let Attachment = require('@models/Attachment');
let Note = require('@models/Note')
let userId = null

// middleware that is specific to this router
router.use(function setUserId (req, res, next) {
	if(userId = req.headers.userId){
		userId = req.headers.userId
	}
	
	next()
})

router.post('/search', function (req, res) {
	Attachment.search(userId, req.body.noteId, req.body.attachmentType)
	.then( data => res.send(data) )
})

router.post('/textsearch', function (req, res) {
	Attachment.textSearch(userId, req.body.searchTerm)
	.then( data => res.send(data) )
})

router.post('/get', function (req, res) {
	Attachment.forNote(userId, req.body.noteId)
	.then( data => res.send(data) )
})

router.post('/update', function (req, res) {
	Attachment.update(userId, req.body.attachmentId, req.body.updatedText, req.body.noteId)
	.then( result => {
		Note.reindex(userId, req.body.noteId)
		.then( data => res.send(data) )
	})
})

router.post('/delete', function (req, res) {
	Attachment.delete(userId, req.body.attachmentId)
	.then( data => res.send(data) )
})

router.post('/upload', upload.single('file'), function (req, res, next) {

	//Create attachment with file information and node id
	const noteId = parseInt(req.body.noteId)

	Attachment.processUploadedFile(userId, noteId, req.file)
	.then( uploadResults => {
		//Reindex note, attachment may have had text
		Note.reindex(userId, noteId)
		.then( data => res.send(uploadResults) )
	})

})


module.exports = router