const { ipcRenderer } = require('electron')
const { Message } = require('./types')
const got = require('got')
const $ = require('jquery')


/**
 * @param {String} server.hostname 	| Hostname of target server
 * @param {u16} server.port 		| Port to use for server
 * @param {String} server.protocol 	| http/https (no colon)
 *
 * @param {String} auth.jwt  | jwt for quick auth
 * @param {u64} auth.id user | id required by most/all endpoints
 *
 */
function rebind_message_box(server, auth, channel_id) {

	$('#message-btn').click( async () => {
		const content = $.trim($('#message-box').val())
		await send(server, auth, channel_id, content) 
		$('#message-box').val('')
	})

	$('#message-box').on('keypress', async (event) => {
		if(event.keyCode == 13 && !event.shiftKey ) {
			const content = $.trim($('#message-box').val())
			await send(server, auth, channel_id, content)
			$('#message-box').val('')
		}
	})
}

/**
 * @param {String} auth.jwt  | jwt for quick auth
 * @param {u64} auth.id user | id required by most/all endpoints
 *
 * @param {String} server.hostname 	| Hostname of target server
 * @param {u16} server.port 		| Port to use for server
 * @param {String} server.protocol 	| http/https (no colon)
 *
 * @param {u64} channel_id   | Channel id to query
 * @param {i64} start_time   | Unix time to start fetching messages from
 * @param {i64} end_time     | Unix time to stop fetching messages from
 *
 * @returns {Message[]}
 *
 * @throws HTTPResponseError
 */
async function get_range(auth, server, channel_id, start_time, end_time, limit) {
	const url = `${server.protocol}://${server.hostname}:${server.port}/message/get_range`

	const response = await got(url, {
		searchParams: {
			id: auth.id,
			jwt: auth.jwt,
			channel_id: channel_id,
			start_time: start_time,
			end_time: end_time,
			limit: limit // backend allows for fucked up values
		},
		responseType: 'json'
	});

	// assming 200 from this point out
	let messages = []
	for(const msg of response.body['messages']) {
		console.log('raw message', msg)
		messages.push(new Message(
			msg['id'], 
			msg['time'], 
			msg['content'], 
			msg['content_type'],
			msg['author_id'],
			msg['name'],
			msg['channel_id']
		))
	}

	console.log(messages)

	rebind_message_box(server, auth, channel_id)
	return messages
}

/**
 * @param {Message} message
 *
 * @description Basically pushes the required html to the dom
 * @returns void
 */
function push_message(message) {
	let a_tag = $('<a>').attr({
		id: `message-${message.uid}`,
		href: '#',
		'class': 'btn btn-link author-name'
	}).text(message.uname)

	// next the content itself
	let content
	if(message.content) {
		content = message.content
	} else {
		content = $('<span>').text('Unsupported content')
	}

	let container = $('<p>').append(a_tag, content).attr('class', 'message')
	$('#messages-list').append( $('<li>').append(container) ) 
}

/**
 * @param {String} auth.jwt  | jwt for quick auth
 * @param {u64} auth.id user | id required by most/all endpoints
 *
 * @param {String} server.hostname 	| Hostname of target server
 * @param {u16} server.port 		| Port to use for server
 * @param {String} server.protocol 	| http/https (no colon)
 *
 * @param {String} channel.description | Description of channel
 * @params {u64} channel.id | channel id to query
 * @returns void
 */
exports.recent_messages = async function (auth, server, channel, start_time, end_time, limit) {
	$('#messages-list').html('')

	const messages = await get_range(auth, server, channel['id'], start_time, end_time, limit)

	for(const message of messages) { 
		console.log(message)
		push_message(message) 
	}
}

/**
 * @param {String} server.protocol
 * @param {String} server.hostname
 * @param {String} server.port
 *
 * @param {String} auth.jwt
 * @param {Number} auth.id
 *
 * @param {Number} channel_id
 */
async function send(server, auth, channel_id, body) {
	const url = `${server.protocol}://${server.hostname}:${server.port}/message/send`
	console.log('sending: ', url)
	// using callbacks for finer grain control of error messages
	got.post(url, {
		searchParams: { 
			id: auth.id, jwt: auth.jwt,
			channel_id: channel_id,
			type: 'text'
		},
		body: body
	})
	.then(
		response => console.log('Sucess: ', response), // all good
		failure => { console.log('Failed to send: ', server, auth, channel_id, failure.options) }
	)
	
}
