//
// All actions in noteController.js
//


const db = require('@config/database')

const Note = require('@models/Note')

let ShareNote = module.exports = {}

// Share a note with a user, given the correct username
ShareNote.addUser = (userId, noteId, rawTextId, username) => {
	return new Promise((resolve, reject) => {

		let shareUserId = null
		let newNoteShare = null

		//Check that user actually exists
		db.promise().query(`SELECT id FROM user WHERE username = ?`, [username])
		.then((rows, fields) => {

			if(rows[0].length == 0){
				throw new Error('User Does Not Exist')
			}

			shareUserId = rows[0][0]['id']

			//Check if note has already been added for user
			return db.promise()
			.query('SELECT id FROM note WHERE user_id = ? AND note_raw_text_id = ?', [shareUserId, rawTextId])
			
		})
		.then((rows, fields) => {

			if(rows[0].length != 0){
				throw new Error('User Already Has Note')
			}

			//Lookup note to share with user, clone this data to create users new note
			return db.promise()
			.query(`SELECT * FROM note WHERE id = ? LIMIT 1`, [noteId])
		})
		.then((rows, fields) => {

			newNoteShare = rows[0][0]

			//Modify note with the share attributes we want
			delete newNoteShare['id']
			delete newNoteShare['opened']
			newNoteShare['share_user_id'] = userId //User who shared the note 
			newNoteShare['user_id'] = shareUserId //User who gets note

			//Setup db colums, db values and number of '?' to put into prepared statement
			let dbColumns = []
			let dbValues = []
			let escapeChars = []

			//Pull out all the data we need from object to create prepared statemnt
			Object.keys(newNoteShare).forEach( key => {
				escapeChars.push('?')
				dbColumns.push(key)
				dbValues.push(newNoteShare[key])
			})
		
			//Stick all the note value back into query, insert updated note
			return db.promise()
			.query(`INSERT INTO note (${dbColumns.join()}) VALUES (${escapeChars.join()})`, dbValues)
		})
		.then((rows, fields) => {

			//Success!
			return resolve(true)
		})
		.catch(error => {
			// console.log(error)
			resolve(false)
		})
	})
}

// Get users who see a shared note
ShareNote.getUsers = (userId, rawTextId) => {
	return new Promise((resolve, reject) => {
		db.promise()
		.query(`
			SELECT username, note.id as noteId
			FROM note 
			JOIN user ON (user.id = note.user_id)
			WHERE note_raw_text_id = ?
			AND share_user_id = ?
			AND user_id != ?
			`, [rawTextId, userId, userId])
		.then((rows, fields) => {

			//Return a list of user names
			return resolve (rows[0])
		})
	})
}

// Remove a user from a shared note
ShareNote.removeUser = (userId, noteId) => {
	return new Promise((resolve, reject) => {
		
		//note.id = noteId, share_user_id = userId
		db.promise()
		.query('SELECT user_id FROM note WHERE id = ? AND share_user_id = ?', [noteId, userId])
		.then( (rows, fields) => {

			//User has shared this note, with this user
			if(rows[0].length == 1 && Number.isInteger(rows[0][0]['user_id'])){

				Note.delete(rows[0][0]['user_id'], noteId)
				.then( result => {
					resolve(result)
				})

			} else {
				return resolve(false)
			}

		})


	})
}