<?php
	require_once('classes.php');

	header('Location: display.php');
	session_start();

	//input variables
	$existingSites = (!isset($_POST['existingSites']) || empty($_POST['existingSites'])) ? 'x' : trim($_POST['existingSites']); //if existingSites is empty, we set it to x; this is necessary so that there is no just a space on the command line
	$candidateSites = !isset($_POST['candidateSites']) ? '' : trim($_POST['candidateSites']);
	$state = !isset($_POST['state']) ? 'MULTI-STATE' : trim($_POST['state']);
	$numSites = !isset($_POST['numSites']) ? 0 : trim($_POST['numSites']);
	$radius = !isset($_POST['radius']) ? 20 : trim($_POST['radius']); //if k-median is selected, radius will be null, so we arbitrarily set it to 20
	$algorithm = !isset($_POST['algorithm']) ? 'error' : $_POST['algorithm'];
	$useCapacitatedModel = isset($_POST['useCapacitatedModel']);
	//$multiState = isset($_POST['multiState']);
	$multiState = false; //disable multi-state calculations for performance reasons

	//this generates $validInput and $error if applicable
	require_once('validateInput.php');
	
	//input has now been verified, so we can proceed
	if($validInput) {
		$populationZCTA = new StatePopulationZCTA('data/2010CensusPopulation.db', $state);

		//remove elements from $existingSites which are erroneous to avoid displaying the erroneous data
		if($existingSites != 'x')
			foreach($existingSites as $key => $existingSite) {
				if(!$populationZCTA->containsZCTA($existingSite))
					unset($existingSites[$key]);
			}
	
		//generate string of comma-separated ZIP codes for the command line
		if($existingSites != 'x') {
			foreach($existingSites as $existingSite)
				$existingSitesString .= $existingSite . ',';
			$existingSitesString = rtrim($existingSitesString, ','); //remove trailing ,
		} else
			$existingSitesString = 'x';
		
		foreach($candidateSites as $candidateSite)
			$candidateSitesString .= $candidateSite . ',';
		$candidateSitesString = rtrim($candidateSitesString, ','); //remove trailing ,
		
		//the capacity is the total state population divided by the total number of sites we will end up with after the algorithm is run
		$capacity = 0;
		if($useCapacitatedModel)
			$capacity = $populationZCTA->getStatePopulation() / ((count($candidateSites) < $numSites ? count($candidateSites) : $numSites) + ($existingSites == 'x' ? 0 : count($existingSites)));
		
		//now we call the external Java code and parse the text output by throwing the selected sites into an array
		$output = shell_exec("java -Xmx512m -jar java/sentinelCalculator.jar data/2010CensusPopulation.db \"$state\" $numSites $radius " . ($useCapacitatedModel == true ? 'true' : 'false') . " $existingSitesString $candidateSitesString $capacity $algorithm");
		$output = explode("\n", $output);

		//the offset is used to offset the string output from the Java code below
		//if we are doing a multi-state calculation, the state population won't be outputted, so there will be 1 less line to read
		$offset = $populationZCTA->isMultiState() ? 1 : 0;

		if(preg_match('/.+: (.+)/', $output[2 - $offset], $matches))
			$existingSitesStats = $matches[1];
		else
			$_SESSION['error'] = 'Error 1. There was a problem computing the selected sites.<br />';
			
		if(preg_match('/.+: (.+)/', $output[3 - $offset], $matches))
			$selectedSitesStats = $matches[1];
		else
			$_SESSION['error'] = 'Error 2. There was a problem computing the selected sites.<br />';
			
		if(preg_match('/.+: (.+)/', $output[4 - $offset], $matches))
			$totalStats = $matches[1];
		else
			$_SESSION['error'] = 'Error 3. There was a problem computing the selected sites.<br />';
			
		if($numSites > 0) {
			if(preg_match_all('/\d{5}/', $output[6 - $offset], $matches)) {
				$selectedSites = array();
				foreach($matches[0] as $match)
					array_push($selectedSites, $match);
			} else
				$_SESSION['error'] = 'Error 4. There was a problem computing the selected sites.<br />';
		}
		
		$_SESSION['populationZCTA'] = $populationZCTA;
		$_SESSION['existingSites'] = $existingSites == 'x' ? array() : $existingSites;
		$_SESSION['selectedSites'] = $selectedSites;
		$_SESSION['radius'] = $radius;
		$_SESSION['existingSitesStats'] = $existingSitesStats;
		$_SESSION['selectedSitesStats'] = $selectedSitesStats;
		$_SESSION['totalStats'] = $totalStats;
	} else
		$_SESSION['error'] = $error;
?>
