//
// 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
		const cleanUser = username.toLowerCase().trim()

		//Check that user actually exists
		db.promise().query(`SELECT id FROM user WHERE LOWER(username) = ?`, [cleanUser])
		.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) => {

			//Update note share status to 2
			return db.promise()
			.query('UPDATE note SET shared = 2 WHERE id = ?', [noteId])

		})
		.then((rows, fields) => {
			//Success!
			return resolve({'success':true, shareUserId})
		})
		.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) => {

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

		let rawTextId = null
		let removeUserId = null
		
		//note.id = noteId, share_user_id = userId
		db.promise()
		.query('SELECT note_raw_text_id, user_id FROM note WHERE id = ? AND share_user_id = ?', [noteId, userId])
		.then( (rows, fields) => {

			rawTextId = rows[0][0]['note_raw_text_id']
			removeUserId = rows[0][0]['user_id']

			//Delete note entry for other user - remove users access
			if(removeUserId && Number.isInteger(removeUserId)){
				//Delete this users access to the note
				return Note.delete(removeUserId, noteId)

			} else {
				
				return new Promise((resolve, reject) => { resolve(true) })
			}

		})
		.then(stuff => {
			resolve(true)
		})
		.catch(error => {
			console.log(error)
			resolve(false)
		})


	})
}