<?
/** NAF League XML parser.
 *
 * Parses the XML data provided by NAF for leagues part of the QUILT system.
 * 
 * This code is released without any warranties or guarantees of functionality.
 * Feel free to use it in any project, commercial or not, as you see fit.
 *
 * @author Christer Kaivo-oja
 */
class LeagueParser {
  var $xmlParser;
  var $error;
  var $currentIndex;
  var $currentVar;

  var $table;

  /** Contructor. Initiates the class.
   */
  function LeagueParser() {
    $this->xmlParser = xml_parser_create();
    xml_set_object($this->xmlParser, &$this);
    xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($this->xmlParser, XML_OPTION_SKIP_WHITE, 0);

    xml_set_element_handler($this->xmlParser, "handleStartElement", "handleEndElement");
    xml_set_character_data_handler($this->xmlParser, "handleCharacterData");
  }

  /** Parses a string containing the XML data downloaded from the NAF site.
   *
   * @param $data The string containing the XML data.
   *
   * @returns On succes, returns TRUE. On failure, returns FALSE.
   */
  function parse($data) {
    $this->currentVar = false;
    $this->currentIndex = -1;
    $this->table = array();
    
    $xmlOk = xml_parse($this->xmlParser, $data);
    $errCode = xml_get_error_code($this->xmlParser);

    if (!$xmlOk) {
      $this->error = "Error while parsing XML data ($errCode):<br />"
                    .xml_error_string($errCode);
    }
    xml_parser_free($this->xmlParser);
    if ($xmlOk)
      return true;

    return false;
  }

  // Internal handleStartElement method. Processes the start elements
  function handleStartElement($parser, $name, $attr) {
    if ($name == 'team')
      $this->currentIndex++;

    $this->currentVar = $name;
  }

  // Internal handleEndElement method. Processes the closing tags.
  function handleEndElement($parser, $name) {
  }

  // Internal handleCharacterData method. Extracts the actual content of the XML into the proper place
  function handleCharacterData($parser, $data) {
    $data = trim($data);
    if (strlen($data) > 0) {
      if ($this->currentIndex >= 0)
        $this->table[$this->currentIndex][$this->currentVar] = $data;
      else {
        $var = $this->currentVar;
        $this->$var = $data;
      }
    }
  }
}


// Generate a quick HTML header
echo "<html><head><title>Wodell Coach Stats</title></head><body>";

$league = "Wodell";
$user = "Deathwing";

  // Fetch the XML data from the NAF website using the CURL library.
  $url = 'http://www.bloodbowl.net/leagues/'.urlencode($user).'/'.urlencode($league).'.xml';
  $c = curl_init($url);
  curl_setopt($c, CURLOPT_RETURNTRANSFER,1);
  $file = curl_exec($c);
  curl_close($c);

  // Set up the parser class
  $p = new LeagueParser();
  // ... and parse the fetched data
  $ok = $p->parse($file);

  if ($ok) {
    // Trivial helper function
    function linkify($team, $url) {
      return strlen($url) == 0 ?
              $team : 
              "<a href=\"$url\">$team</a>";
    }
    // Generate some simple output based on the parsed data
    echo '<h1>'.$p->name.' Coach Stats</h1>';
?>
	<table border="1">
	<tr bgcolor="#cccccc">
		<th>&nbsp;</th>
		<th>coach</th>
		<th>Played</th>
		<th>Won</th>
		<th>Tied</th>
		<th>Lost</th>
		<th>Win %</th>
		<th>Tie %</th>
		<th>Loss %</th>
		<th>TD Diff</th>
		<th>Cas Diff</th>
	</tr>
<?

    $cArr = array();
    foreach ($p->table as $team) {
    	$coach = $team[coach];
	if (!isset($cArr[$coach])) {
		$cArr[$coach] = array();
	    	$cArr[$coach]['won'] = 0;
    		$cArr[$coach]['tied'] = 0; 
	    	$cArr[$coach]['lost'] = 0;
		$cArr[$coach]['tddiff'] = 0;
		$cArr[$coach]['casdiff'] = 0;
	}
	$cArr[$coach]['coach'] = $coach;
    	$cArr[$coach]['won'] += $team[seasonwins];
    	$cArr[$coach]['tied'] += $team[seasonties];
    	$cArr[$coach]['lost'] += $team[seasonlosses];
	$cArr[$coach]['tddiff'] += $team[seasontdfor] - $team[seasontdagainst];
	$cArr[$coach]['casdiff'] += $team[seasoncasfor] - $team[seasoncasagainst];
    }

    function p($num, $total) {
    	if ($total == 0)
		return 0;
	return $num/$total;
    }
    function cmp($a, $b) {
    	$gamesA = $a['won'] + $a['tied'] + $a['lost'];
	$gamesB = $b['won'] + $b['tied'] + $b['lost'];

	$pa = p($a['won'], $gamesA);
	$pb = p($b['won'], $gamesB);
	if ($pa < $pb)
		return 1;
	if ($pa > $pb)
		return -1;

	$pa = p($a['tied'], $gamesA);
	$pb = p($b['tied'], $gamesB);
	if ($pa < $pb)
		return 1;
	if ($pa > $pb)
		return -1;

	if ($a['tddiff'] < $b['tddiff'])
		return 1;
	if ($a['tddiff'] > $b['tddiff'])
		return -1;
		
	if ($a['casdiff'] < $b['casdiff'])
		return 1;
	if ($a['casdiff'] > $b['casdiff'])
		return -1;
	
	return $a['coach'] < $b['coach'] ? 1 : -1;
    }

    usort($cArr, "cmp");
    $num = 0;
    while (list($key, $c) = each($cArr)) {
    	$num++;
	$played = $c['won'] + $c['tied'] + $c['lost'];
        echo "<tr align=\"center\">"
	    ."<td align=\"right\">$num</td>"
	    ."<td align=\"left\">".$c['coach']."</td>"
	    ."<td>".($played+0)."</td>"
	    ."<td>".($c['won']+0)."</td>"
	    ."<td>".($c['tied']+0)."</td>"
	    ."<td>".($c['lost']+0)."</td>"
	    ."<td>".round(100*p($c['won'],$played))."</td>"
	    ."<td>".round(100*p($c['tied'],$played))."</td>"
	    ."<td>".round(100*p($c['lost'],$played))."</td>"
	    ."<td>".($c['tddiff']+0)."</td>"
	    ."<td>".($c['casdiff']+0)."</td>"
	    ."</tr>";
    }
?>
	</table>

<?
  }
  else {
    // Something went wrong with the parsing...
    echo $p->error;
  }

// All done. Let's close the html just to be nice
echo "</body></html>";
?>