const { ipcRenderer }  = require('electron')
const got = require('got')
const channels = require('./channels.js')


function push_srv(remote, user, enabled) {
	let classes = 'btn btn-outline-secondary btn-nav-settings'
	if(!enabled) { classes += ' disabled' }

	let btn = $('<input>').attr({
		type: 'button',
		'class': classes,
		id: remote['hostname'],
		value: remote['name']
	})

	$('#server-list').append(btn)
	let cb = async () => { await channels.list(remote, user) }
	$(`#${remote['hostname']}`).on('click', cb)
}

/**
 * @param {String} protocol http|https
 * @param {String} host Just the hostname one.two.xyz
 * @param {u16} port Port to use
 * @param {String} user.secret
 * @param {Number} user.id
 *
 * @returns {String|null} JWT 
 */
async function login(protocol, host, port, user) {
	const url = `${protocol}://${host}:${port}/login`
	const response = await got(url, {
		searchParams: { id: user['id'], secret: user['secret'] },
		responseType: 'json',
		// If DNS is seriously taking this long we honestly should just give up
		timeout: {
			lookup: 500
		}
	})
	return response.body['jwt']
}
exports.login = login


/**
 * @returns {Config} whole config to use in ui building back in DOM-land
 */
exports.init = async function() {
	// First we fetch the in-memnory configuration
	const config = await ipcRenderer.invoke('config-request')

	for(const index in config.data['servers']) {
		const remote = config.data['servers'][index]['server']
		const user = config.data['servers'][index]['user']

		try {
			const jwt = await login(remote['protocol'], remote['hostname'], remote['port'], user)
			config.data['servers'][index]['user']['jwt'] = jwt
			user['jwt'] = jwt

			push_srv(remote, user, true);
		} catch (err) {
			push_srv(remote, user, false)
			const e_container = { error: err, server: remote, creds: user }
			console.log('Failure to communicate with server: ', e_container)
		}
	}

	await ipcRenderer.invoke('config-update', config)
	return await ipcRenderer.invoke('config-request')
}
