/**
 * This handles user registration.
 *
 * The form must have the following fields:
 * + UID		The user's user id to login
 * + EMAIL		The users's email address - to receive tokens
 * + FULLNAME	The user's full name
 * + PASS		The users's preferred password
 * + CITY		The user's city
 * + COUNTRY	The user's country - 3 letter ISO code
 * + PCODE		THe user's postal code
 */

var CONTROL_SQRL		= '1';

require('http.js','HTTPRequest');
load('ansitex/load/qrcode-make.js');
load('frame.js');

log(LOG_DEBUG,'+ Control SQRL-LOGIN loaded');

function sqrllogin() {
	var complete = false;
	var cancel = false;

	log(LOG_DEBUG,'OPTIONS: '+JSON.stringify(loadOptions('sqrl')));
	var sqrl = loadOptions('sqrl');
	var http = new HTTPRequest();
	http.SetupGet(sqrl.auth_path,undefined,sqrl.auth_url);
	http.request_headers.push('Accept: application/json');

	try {
		http.SendRequest();
		http.ReadResponse();
		log(LOG_INFO,'SQRL: '+JSON.stringify(http.body));

		var data = http.body
			.split('')
			.map(function(x) {return x.charCodeAt(0)});
		var qr = qrcodegen.QrCode.encodeBinary(data,qrcodegen.QrCode.Ecc.LOW);

		var subframe = new Frame((viewdata ? VIEWDATA_FRAME_WIDTH : ANSI_FRAME_WIDTH-qr.size-2),2,(viewdata ? qr.size/2 : qr.size+2),22,BG_BLACK|LIGHTGRAY);
		fo.qrcode(qr,subframe);

		fo.sendBaseline('CANCEL_MSG',false);

		// Loop and see if the user has logged in
		var nut = http.body.substr(http.body.indexOf('nut='),68);

		var read = '';
		while (read !== '2') {
			read = console.inkey(K_NONE,1000);

			if (read == 2)
				cancel = true;

			http = new HTTPRequest();
			http.SetupGet(sqrl.auth_post+'?'+nut,undefined,sqrl.auth_url);
			http.request_headers.push('Accept: application/json');

			log(LOG_DEBUG,'Checking NUT in ['+nut+']');
			http.SendRequest();
			http.ReadResponse();

			switch (http.response_code) {
				case 404:
					log(LOG_DEBUG,'- NUT not Authorised yet.');
					break;

				case 200:
					var result = JSON.parse(http.body);

					if (result.isReady) {
						log(LOG_INFO,'NUT: '+result.msg);
						log(LOG_INFO,'NEXT: '+result.nextPage);
						if (result.msg == 'SQRL authenticated') {
							log(LOG_DEBUG,'Getting Authenticated User ['+result.nextPage+']');
							http = new HTTPRequest();
							http.SetupGet(result.nextPage,undefined,'');
							http.request_headers.push('Accept: application/json');

							http.SendRequest();
							http.ReadResponse();

							log(LOG_DEBUG,'Getting Authenticated User Response ['+http.response_code+']');
							if (http.response_code == 200) {
								var sqrluser = http.body.substr(0,40);
								var username = 'S'+sqrluser.substr(0,24)
								log(LOG_DEBUG,'Getting Authenticated sqrluser ['+JSON.stringify(sqrluser)+']');

								// Look through our user base for an existing user
								var uid = system.matchuser(username);

								log(LOG_DEBUG,'Getting Authenticated UID ['+JSON.stringify(uid)+']');
								if (! uid) {
									log(LOG_DEBUG,'New User ['+username+'] with pass ('+sqrluser+')');
									var user = system.new_user(username);
									log(LOG_DEBUG,'New User ['+JSON.stringify(user.number)+']');
									user.name = username;
									user.security.password = sqrluser;
									user.handle = username.substr(0,8);
									user.location = 'Earth';
									user.zipcode = '000';
									user.netmail = username+'@'+system.inet_addr;

									user.comment = 'ANSITEX registered user - with SQRL';
									bbs.user_sync();

								} else {
									user = new User(uid);
								}

								log(LOG_DEBUG,'Getting Authenticated USER ['+JSON.stringify(user.number)+']');

								// Existing user, we'll exit here
								if (bbs.login(user.name,null,user.security.password)) {
									log(LOG_DEBUG,'  - User:'+JSON.stringify(user.number));
									bbs.logon();
									log(LOG_DEBUG,'  - SEND TO EXIT:');

									complete = true;
									read = '2';
									action = ACTION_EXIT;
									if (typeof subframe === 'object')
										subframe.close();

									break;

								} else {
									log(LOG_ERROR,'- Login Failed? ');
								}

							} else {
								log(LOG_ERROR,'- Unhandled User Details: '+http.response_code);
							}

						} else {
							log(LOG_ERROR,'- Unhandled isReady msg: '+result.msg);
						}

						complete = true;
						if (typeof subframe === 'object')
							subframe.close();

						// We are done
						read = '2';

					} else {
						log(LOG_ERROR,'- Unhandled isReady: '+result.isReady);

						// We are done
						read = '2';
						cancel = true;
					}
					break;

				default:
					log(LOG_ERROR,'- Unhandled response code: '+http.response_code);

					// We are done
					read = '2';
					cancel = true;
			}
		}

	} catch (err) {
		log(LOG_INFO,'SQRL Error: '+err+' '+JSON.stringify(sqrl));
		cancel = true;
	}

	if (cancel) {
		complete = true;
		if (typeof subframe === 'object')
			subframe.close();
		action = ACTION_GOTO;
		next_page = { frame: 98,index: 'a' };
	}

	// Called before processing for a field
	Object.defineProperty(this, 'getName', {
		get: function () {
			return 'SQRL-LOGIN';
		}
	});

	Object.defineProperty(this, 'isComplete', {
		get: function () {
			return complete;
		}
	});

	// Nothing to do here
	this.handle=function(read) {
		log(LOG_DEBUG,'Control SQRL-LOGIN handle() start. ('+read+')');

		return read;
	}

	/*
	this.prefield=function() {

	}

	this.process=function() {
		subframe.close();
		frame.close();
	}
	*/
}

this;