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

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

let QuickNote = module.exports = {}


QuickNote.get = (userId) => {
	return new Promise((resolve, reject) => {

		db.promise()
		.query(`
			SELECT id, text FROM note WHERE quick_note = 1 AND user_id = ? LIMIT 1
			`, [userId])
		.then((rows, fields) => {

			//Quick Note is set, return note text
			if(rows[0].length == 1){
				resolve({
					id: rows[0][0].id,
					text: rows[0][0].text
				})
			}

			resolve({
				id: null,
				text: 'Enter something to create a quick note.'
			})
		})
		.catch(console.log)
	})
}

QuickNote.update = (userId, pushText) => {
	return new Promise((resolve, reject) => {

		//Process pushText, split at \n (new lines), put <p> tags around each new line
		let broken = '<blockquote>' +
			pushText.split(/\r?\n/).map( (line, index) => {

			let clean = line
				.replace(/&[#A-Za-z0-9]+;/g,'') //Rip out all HTML entities
				.replace(/<[^>]+>/g, '') //Rip out all HTML tags

			if(clean == ''){ clean = '&nbsp;' }
			let newLine = ''
			if(index > 0){ newLine = '<br>' }

			//Return line wrapped in p tags
			return `${newLine}<span>${clean}</span>`

		}).join('') + '</blockquote>'

		db.promise()
		.query(`
			SELECT id, text, color, pinned, archived
			FROM note WHERE quick_note = 1 AND user_id = ? LIMIT 1
			`, [userId])
		.then((rows, fields) => {

			//Quick Note is set, push it the front of existing note
			if(rows[0].length == 1){

				let d = rows[0][0] //Get row data

				//Push old text behind fresh new text
				let newText = broken +''+ d.text

				//Save that, then return the new text
				Note.update(userId, d.id, newText, d.color, d.pinned, d.archived)
				.then( saveResults => {
					resolve({
						id:d.id,
						text:newText
					})
				})

			} else {

				//Create a new note with the quick text submitted.
				Note.create(userId, broken, 1)
				.then( insertId => {
					resolve({
						id:insertId,
						text:broken
					})
				})
			}
		})
		.catch(console.log)
	})

	//Lookup quick note, 

	//Note.create(userId, 'Quick Note', 1)

}

QuickNote.create = (userId, noteText) => {
	return new Promise((resolve, reject) => {

		if(userId == null || userId < 10){ reject('User Id required to create note') }

		const created = Math.round((+new Date)/1000)

		db.promise()
		.query('INSERT INTO note (user_id, text, created) VALUES (?,?,?)', [userId, noteText, created])
		.then((rows, fields) => {
			resolve(rows[0].insertId) //Only return the new note ID when creating a new note
		})
		.catch(console.log)
	})
}