#!/usr/bin/perl -w

# Test the API.
use strict;
use warnings;
use LWP::UserAgent;
use Data::Dumper;
use JSON;

my $url = shift(@ARGV) || "http://www.dev1.siikir.com/api";
my $ua  = new LWP::UserAgent();

# App info
my $app = {
	version => "1.0",
	name    => "debug-app",
};
my $sessid = "";

my @menu = (
	"Authorize app" => \&do_hello,
	"Log in"        => \&do_login,
	"Log out"       => \&do_logout,
	"Register"      => \&do_register,
	"Search nearby" => \&do_nearby,
);
while (1) {
	print "-== API Test Menu ==-\n\n";

	my $n = 1;
	my %map = ();
	for (my $i = 0; $i < scalar(@menu); $i += 2) {
		$map{$n} = [ $menu[$i], $menu[$i+1] ];
		print "$n. $menu[$i]\n";
		$n++;
	}
	print "> ";

	my $ans = <STDIN>;
	chomp $ans;
	if (exists $map{$ans}) {
		print "\n";
		$map{$ans}->[1]->();
	}
	else {
		print "Not a valid option.\n\n";
	}
}

sub do_hello {
	print "Attempting to authorize app...\n";

	my $resp = post("hello", {
		version     => $app->{version},
		application => $app->{name},
	});
}

sub do_login {
	print "Username: ";
	chomp(my $username = <STDIN>);
	print "Password: ";
	chomp(my $password = <STDIN>);

	my $resp = post("login", {
		method   => "login",
		username => $username,
		password => $password,
	});
}

sub do_logout {
	print "Logging out!\n";

	my $resp = post("logout");
}

sub do_register {
	print "Register new account\n";

	my $username = prompt("Username:");
	my $password = prompt("Password:");
	my $dob      = prompt("Birthdate (yyyy-mm-dd):");

	my $nick     = prompt("Nickname:");
	my $email    = prompt("Email:");
	my $sex      = prompt("Gender (male, female):");

	my $zip      = prompt("Zip code:");
	my $geo      = prompt("Geolocation (true or blank):");
	print "Time zone is using -28800 (Pacific Time)\n\n";
	my $tz       = -28800;

	# Register.
	my $resp = post("register", {
		username    => $username,
		password    => $password,
		dob         => $dob,
		name        => $nick,
		email       => $email,
		gender      => $sex,
		zipcode     => $zip,
		geoapi      => $geo,
		timezone    => $tz,
	});
}

sub do_nearby {
	print "Searching for nearby users\n";
	my $page = prompt("Page [1]:") || 1;

	my $resp = post("search", {
		method => "nearby",
		page   => $page,
	});
}

sub prompt {
	my $line = shift;

	print "$line ";
	chomp(my $ans = <STDIN>);
	return $ans;
}

sub post {
	my $api  = shift;
	my $data = shift;

	# Impose the sessid.
	$data->{sessid} = $sessid;

	print "## POST: /api/$api ##\n";
	print Dumper($data) . "\n";

	my $resp = $ua->post("$url/$api", $data);
	if ($resp->is_success) {
		my $reply;
		eval {
			$reply = from_json($resp->content, { utf8 => 1, pretty => 1 });
		}; if ($@) {
			print "DECODE ERROR: $@\n" . $resp->content . "\n";
		}
		print "Reply:\n" . Dumper($reply) . "\n";

		# Cache the sessid.
		$sessid = $reply->{sessid};

		# Error?
		if ($reply->{response} eq "ERR") {
			print "## ERRORS ENCOUNTERED ##\n"
				. join("\n", @{$reply->{error}}) . "\n\n";
		}

		return $reply;
	}
	else {
		die $resp->status_line;
	}
}
