// ======================================================================
// UTORRENT LIBRARY
// Contains functions for working with a remote uTorrent installation.
// ======================================================================

var utorrent_data = {
	'user': '',
	'pass': '',
	'domain': '',
	'port': 0,
};

function utorrent_init(domain, port, user, pass) {
	utorrent_data['user'] = user;
	utorrent_data['pass'] = pass;
	utorrent_data['domain'] = domain;
	utorrent_data['port'] = port;	
}

function utorrent_api(api) {
	return http_getAuth(
		utorrent_data['domain'], utorrent_data['port'], api,
		utorrent_data['user'], utorrent_data['pass']
	);
}

function utorrent_getToken() {
	mudc_console("Retrieving a fresh uTorrent authentication token...");

	var tokenPage = utorrent_api("/gui/token.html");
	
	var token = tokenPage.substring(44, 104);
	if (token.length) {
		return token;
	} else {
		mudc_console("Error retrieving token: \""+tokenPage+"\"");
		return "";
	}
}

function utorrent_torrents() {
	mudc_console("Retrieving list of torrents...");

	var jsonTorrents = utorrent_api("/gui/?list=1&token=" + utorrent_getToken());
	
	if (jsonTorrents.length && jsonTorrents.charAt(0) === '{') {
		return eval(jsonTorrents);
	} else {
		mudc_console("Failed to retrieve list of torrents: \""+jsonTorrents+"\"");
		return [];
	}
}

function utorrent_addByUrl(url) {
	mudc_console("Adding torrent by URL...");
	
	utorrent_api("/gui/?action=add-url&s="+http_escape(url)+"&token="+utorrent_getToken());
}