<?php
defined('_JEXEC') or die('Restricted access!');

jimport('joomla.application.component.view');

/**
 * Races View
 *
 * JPodium is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 2
 * as published by the Free Software Foundation.
 *
 * JPodium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with JPodium; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * @package JPodiumFrontend
 * @subpackage Views
 */

/**
 * Races View
 *
 * @version $Id: view.html.php 247 2010-12-03 20:58:23Z detlefvolmer $
 * @author Detlef Volmer <webmaster@jpodium.de>
 * @package JPodiumFrontend
 * @subpackage Views
 * @copyright Copyright (C) Detlef Volmer www.jpodium.de
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 */
class JPodiumViewRaces extends JView
{
	function display($tpl = null) {
		global $mainframe;

		JHTML::stylesheet('jpodium.css', 'administrator/components/com_jpodium/assets/');

		$raceHeaders = array();		// formatted race header blocks
		$validRaceIDs = array();	// filtered and sorted race IDs
		$resultTables = array();	// results per race as complete HTML table
		$athleteNames = array();	// formatted athlete names
		$classNames = array();		// formatted class short descriptions
		$heatNames = array();		// formatted heat short descriptions

		$results = array();			// results per race; race ID is key

		$athletes = array();		// unfiltered athletes to be displayed out of DB
		$classes = array();			// unfiltered classes to be displayed out of DB
		$countries = array();		// unfiltered countries to be displayed out of DB
		$heats = array();			// unfiltered heats to be displayed out of DB
		$races = array();			// filtered and sorted races to be displayed out of DB
		$teams = array();			// unused array for athletes list query

		$years = array();			// array of years to include in the list
		$seasons = array();			// array of seasons to include in the list

		$racesModel = $this->getModel('races');
		$athletesModel = $this->getModel('athletes');
		$classesModel = $this->getModel('classes');
		$countriesModel = $this->getModel('countries');
		$heatsModel = $this->getModel('heats');
		$resultsModel = $this->getModel('results');

		// make sure long lists are displayed properly
		ini_set('pcre.backtrack_limit', '-1');

		// read the years to display and separate the values; no error checking is done
		$yearsToDisplay = $mainframe->getParams()->get('YearsToDisplay', '');
		if ($yearsToDisplay) {
			$years = explode(",", $yearsToDisplay);
			JArrayHelper::toInteger($years);
		}
		// read the seasons to display and separate the values; no error checking is done
		$seasonsToDisplay = $mainframe->getParams()->get('SeasonsToDisplay', '');
		if ($seasonsToDisplay) {
			$seasons = explode(',', $seasonsToDisplay);
			JArrayHelper::toInteger($seasons);
		}
		// read the ordering direction for the races list
		$dateOrdering = $mainframe->getParams()->get('DateOrdering', 'DESC');
		if ($dateOrdering <> 'ASC')
		$dateOrdering = 'DESC';		// force to valid values, just in case

		$year = JRequest::getVar('year', 0, '', 'int');
		// if URL contains a year, then ignore the $years and $seasons settings and filter to $year only
		if ($year) {
			$seasons = array();			// reset $seasons filter
			$years = array();			// reset $years filter
			$years[0] = (int)$year;		// set $years filter to value in link
		}

		$singleRaceID = $mainframe->getParams()->get('RaceID', '');
		$resultGrouping = $mainframe->getParams()->get('ResultGrouping', 'NO');
		$showFlag = $mainframe->getParams()->get('ShowFlag', 'NO');
		$showTime = $mainframe->getParams()->get('ShowTime', 'NO');
		$showRemark = $mainframe->getParams()->get('ShowRemark', 'YES');
		$showPoints = $mainframe->getParams()->get('ShowPoints', 'NO');

		$labelRemark = $mainframe->GetParams()->get('LabelRemark', '');
		$labelResult = $mainframe->GetParams()->get('LabelResult', '');
		
		if ($singleRaceID) {
			$races = $racesModel->getRaceByID((int)$singleRaceID);
		}
		else {
			$races = $racesModel->getRacesList($years, $seasons, $dateOrdering);
		}

		foreach($races as $race) {
			// create complete HTML for the race header
			$raceHeaders[$race->r_id] = JPodiumHTMLHelper::CreateRaceHeader($race);
			// create array with valid race IDs depending on filter criteria and sorting
			$validRaceIDs[] = $race->r_id;
		}

		// from here on we have a list of valid race IDs we want to display in a given order

		// instantiate the HTML table for the results
		$resultTable = new JPodiumHTMLTable('races');

		if (!empty($validRaceIDs)) {			// are there races to display?
			switch ($resultGrouping) {
				case 'CLASS':
					$order = 'e_cid, e_result ASC';
					// add first column if result grouping is required
					$resultTable->addColumn('center', '10%', JText::_('')); // korrigiert !!!!!!!!!!!!!!!!!!!
					break;
				case 'HEAT':
					$order = 'e_heat, e_result ASC';
					// add first column if result grouping is required
					$resultTable->addColumn('center', '10%', JText::_('Heat'));
					break;
				case 'NO':
				default:
					$order = 'e_result ASC';
					break;
			}
			foreach($validRaceIDs as $validRaceID) {
				$results[strval($validRaceID)] = $resultsModel->getResultsPerRace($validRaceID, $order);
			}
		}

		// create the columns for the result table
		if ($labelResult) {
			$resultTable->addColumn('center', '10%', JText::_('Pos.')); // korrigiert !!!!!!!!!!!!!!!!!!!!
		}
		else {
			$resultTable->addColumn('center', '10%', JText::_('Pos.'));
		}
		$resultTable->addColumn('left', '40%', JText::_('')); // korrigiert !!!!!!!!!!!!!!!!!!!!!!!!!
		if ($showTime) {
			$resultTable->addColumn('right', '10%', JText::_('Time'));
		}
		if ($showPoints) {
			$resultTable->addColumn('center', '10%', JText::_('Points'));
		}
		if ($showRemark) {
			// overwritten label in the menu entry ??
			if ($labelRemark) {
				$resultTable->addColumn('left', '40%', $labelRemark);
			} else {
				$resultTable->addColumn('left', '40%', JText::_('Remark'));
			}
		}

		$athleteNames = $athletesModel->getAthleteNames();
		$athleteCountries = $athletesModel->getAthleteCountries();
		$countryCodes = $countriesModel->getCountryISOCodes();
		$classNames = $classesModel->getClassNames();
		$heatNames = $heatsModel->getHeatNames();

		foreach($validRaceIDs as $validRaceID) {

			$oldclass = 0;		// flag to detect the class change
			$oldheat = 0;		// flag to detect the heat change
			$newGroup = true;	// flag to indicate the bold printing of the class/heat name
			$strClassOrHeat = '';

			if (sizeof($results[$validRaceID]) == 0) {
				$resultTable->addTextSpanRow(JText::_('There are no entries for this race yet.'));
			}
			else {
				foreach($results[strval($validRaceID)] as $race_result) {
					switch ($resultGrouping) {
						case 'CLASS':
							// fine line on class change
							if (($oldclass) && ($oldclass != $race_result->e_cid)) {
								$resultTable->addSeparatorRow();
								$newGroup = true;
							}
							if (array_key_exists($race_result->e_cid, $classNames)) {
								$strClassOrHeat = '<b>' . $classNames[strval($race_result->e_cid)] . '</b>';
							}
							break;
						case 'HEAT':
							// fine line on heat change
							if (($oldheat) && ($oldheat != $race_result->e_heat)) {
								$resultTable->addSeparatorRow();
								$newGroup = true;
							}
							if (array_key_exists($race_result->e_heat, $heatNames)) {
								$strClassOrHeat = '<b>' . $heatNames[strval($race_result->e_heat)] . '</b>';
							}
							break;
						default:
							break;
					}

					// open a row for individual addition of cells to this row
					$resultTable->openRow();

					if ($resultGrouping != 'NO') {
						if ($newGroup) {
							$resultTable->addCellInRow($strClassOrHeat);
						}
						else {
							$resultTable->addCellInRow();
						}
					}
						
					$resultTable->addCellInRow($race_result->e_result);

					if (array_key_exists($race_result->e_fid, $athleteNames)) {
						$flag = '';
						if ($showFlag) {
							if (array_key_exists($race_result->e_fid, $athleteCountries)) {
								if (JPluginHelper::isenabled('content', 'jpocountries')) {
									$countryIndex = $athleteCountries[strval($race_result->e_fid)];
									if ($countryIndex) {
										$isoCode = strtolower($countryCodes[$countryIndex]);
									}
									else {
										$isoCode = 'blank';
									}
									$flag = JHTML::_('content.prepare', '{jpocountry iso=' . $isoCode . '|type=flag}&nbsp;');
								}
							}
						}
						$resultTable->addCellInRow($flag . $athleteNames[strval($race_result->e_fid)]);
					}
					else {
						$resultTable->addCellInRow();
					}
						
					if ($showTime) {
						$resultTable->addCellInRow($race_result->e_time);
					}
					if ($showPoints) {
						$resultTable->addCellInRow($race_result->e_points);
					}
					if ($showRemark) {
						$resultTable->addCellInRow($race_result->e_comment);
					}

					// all cells added -> close row
					$resultTable->closeRow();

					$oldclass = $race_result->e_cid;	// save last class ID
					$oldheat = $race_result->e_heat;	// save last heat ID
					$newGroup = false;
				} // end-foreach
			}
			// read the table and reset all rows
			$resultTables[$validRaceID] = $resultTable->getFullHTML(TRUE);
		} // end-foreach

		$this->assignRef('raceHeaders',		$raceHeaders);
		$this->assignRef('validRaceIDs',	$validRaceIDs);
		$this->assignRef('resultTables',	$resultTables);
		$this->assignRef('year',			$year);	// only used for linkbar

		parent::display($tpl);
	}
}