// Requesting channel data here
const $ = require('jquery')
const got = require('got')

const msg = require('./messages.js')


const ANY_CHANNEL = 0
const VOICE_KIND = 1
const TEXT_KIND = 2


/**
 * Channel button id's have the format of ${hostname}:${channel['name']}
 * Helper function that literally just pushes out some bs to the DOM
 *
 * @param {String} server.hostname
 * @param {u16} server.port
 * @param {String} server.protocol
 *
 * @param {u64} user.id
 * @param {String} user.jwt
 *
 * @param {u64} channel.id
 * @param {String} channel.name
 * @param {String} channel.description
 * @param {i32} channel.kind
 */
function push(server, user, channel) {
	$('#channels-list').append(
		$('<li>').append(
			$('<p>').append(
				$('<button>').attr({
					'class': 'btn btn-outline-secondary btn-nav-settings channel-btn',
					id: `${server.hostname}:${channel['name']}`,
				}).text(channel['name'])
			)
		)
	)
	// Not using jquery for this because it breaks with weird id names really easily
	let ref = document.getElementById(`${server.hostname}:${channel['name']}`)
	ref.addEventListener('click', function() {
		// now for the actual handler where we deal with clicks
		$('#channel-name').text('#' + channel['name'])
		$('#channel-description').text(channel['description'])

		const now = Math.floor(new Date().getTime() / 1000)
		const yesterday = now - (60 * 60 * 48)

		msg.recent_messages(user, server, channel, yesterday , now, 1000)
		.then(()=>{}, reason => {
			console.error(reason)
		})
	})
}
/**
 * Listener callback for actually getting a list of channels
 * @param {Object} server Object containing server configuration
 * @param {Object} user Object containing user access data
 * 
 */
exports.list = async function(server, user) {

	// TODO: add some kind of caching system here: should probably check for some kind of cache here but hey fuck it right?
	$('#channels-list').html('')
	$('#server-name').text(server['name'])

	try {
		const url = `${server['protocol']}://${server['hostname']}:${server['port']}/channels/list`
		const response = await got(url, {
			searchParams: { id: user['id'], jwt: user['jwt'], kind: ANY_CHANNEL },
			responseType: 'json'
		})

		const channels = response.body['channels']


		for(const channel of channels) { 
			console.log(channel)
			push(server, user, channel)
		}

	} catch (err) {
		console.log(err)
		console.log(err['name'])
	}
}
