<?php
# CSE 190 M, Spring 2012
# This web service accepts query parameters 'name' and 'gender'
# and searches rank.txt for a line of data about that name/gender
# and outputs the data on that line in XML format.
# If the person is not found in the file, produces an HTTP 410 error.
#
# Example line of data from the file (name, gender, then 12 decade ranks):
# Aaron m 147 193 187 199 250 237 230 178 52 34 34 41 55
#
# Example XML output:
# <baby name="Aaron" gender="m">
#   <rank year="1980">147</rank>
#   <rank year="1900">193</rank>
#   ...
# </baby>

$name = get_parameter("name");
$gender = get_parameter("gender");

# search the input file for the line about the given name/gender
$matching_line = "";
$lines = file("rank.txt", FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
	if (preg_match("/^$name $gender /", $line)) {
		$matching_line = $line;
		break;
	}
}

if ($matching_line) {
	$json = generate_json($line, $name, $gender);
	header("Content-type: application/json");
	print json_encode($json);
} else {
	# this person/gender was not found; issue HTTP error 410
	header("HTTP/1.1 410 Gone");
	die("HTTP/1.1 410 Gone - There is no data for this name/gender.");
}


# Creates and returns JSON representation for the given line of data.
# for the data, "Aaron m 147 193 187 199 250 237 230 178 52 34 34 41 55",
# would produce the following JSON:
#{
#  "name": "Morgan",
#  "gender": "m",
#  "rankings": [375, 410, 392, 478, 579, 507, 636, 499, 446, 291, 278, 332, 518]
#}
function generate_json($line, $name, $gender) {
	# Aaron m 147 193 187 199 250 237 230 178 52 34 34 41 55
	$year = 1890;
	$tokens = explode(" ", $line);
	$data = array(
	  "name" => $name,
	  "gender" => $gender,
	  "rankings" => array_map('intval',array_slice($tokens, 2))
	);
	return $data;
}

# Returns the value of the given query parameter.
# If the parameter has not been passed, issues an HTTP 400 error.
function get_parameter($name) {
	if (isset($_GET[$name])) {
		return $_GET[$name];
	} else {
		header("HTTP/1.1 400 Invalid Request");
		die("HTTP/1.1 400 Invalid Request - you forgot to pass a '$name' parameter.");
	}
}
?>