const { ipcRenderer } = require('electron')
const $ = require('jquery')
const auth = require('./auth.js')

exports.add_server_to_config = async function() {
	$('#admin-json-err').html('<div class="spinner-border" role="status"> <span class="sr-only">Loading...</span> </div>')

	try {
		let data = JSON.parse($('#admin-json').val())
		let config = await ipcRenderer.invoke('config-request')
		if(!config.data['servers']) {
			config.data['servers'] = []
		}
		config.data['servers'].push(data)

		await ipcRenderer.invoke('config-update', config)

		try {
			await auth.login(
				data['server']['protocol'],
				data['server']['host'],
				data['server']['port'],
				data['user']
			)
			$('#admni-json-err').text('=|:^)')
		} catch(err) {
			// probably a bad config that got parsed properly
			if(err.name == 'TypeError') {
				$('#admin-json-err').text("New server config did not have required JSON values to login but was saved")
			} else {
				$('#admin-json-err').text("Config saved but couldn't login")
			}
		}
	} catch(err) {
		$('#admin-json-err').text('Failed to setup new config')
		console.log(err)
	}
}
