<?php
	include_once("db.php");

	//make result object
	$result = array();
	$result['ok'] = false;

	//get post data
	$postdata = file_get_contents("php://input");
	$post = json_decode($postdata, true);

	$idchampionship = $post['idchampionship'];
	$tier = $post['tier'];
	$poule = $post['poule'];

	//fetch teams
	$teamfetch = pg_prepare($dbconn, "teamfetch", "select team.*, team.name teamname from team inner join team_poule using (idteam, idchampionship) where tier = $1 and poule = $2 and idchampionship = $3");
	// $result['lasterror'].=pg_last_error()."\n";
	$racefetch = pg_prepare($dbconn, "racefetch", "select *,
	(select extract(epoch from avg(laptime)) from valid_laptimes where idrace = race.idrace) avglaptime,
	(select extract(epoch from sum(laptime)) from valid_laptimes where idrace = race.idrace)
			+(select coalesce(sum(penaltyseconds), 0) from comment where idrace = race.idrace)
	 		sumlaptime 
	from race where tier = $1 and poule = $2 and idchampionship = $3 and idteam = $4");
	// $result['lasterror'].=pg_last_error()."\n";

	// $laptimefetch = pg_prepare($dbconn, "laptimefetch", "select vm1.idrace, extract(epoch from vm2.cleaneduptime-vm1.cleaneduptime) laptime from valid_measurements vm1 inner join valid_measurements vm2 on vm1.idrace = vm2.idrace and vm1.idmeasurement != vm2.idmeasurement and vm1.cleaneduptime < vm2.cleaneduptime and vm2.cleaneduptime = (select min(cleaneduptime) from valid_measurements vm3 where vm3.cleaneduptime>vm1.cleaneduptime and vm3.idrace = vm1.idrace) where vm1.idrace = $1 order by vm1.idrace, laptime");
	// $laptimefetch = pg_prepare($dbconn, "laptimefetch", "
	// with result as (
	// with sortedtimes as
	// 	(select idrace, cleaneduptime, row_number() over (partition by idrace order by cleaneduptime) from valid_measurements order by idrace, cleaneduptime)
	// select idrace, row_number lapnr, cleaneduptime, (select cleaneduptime-st1.cleaneduptime from sortedtimes where row_number = st1.row_number+1 and idrace = st1.idrace) laptime from sortedtimes st1 where row_number <= (select sum(laps) from drive where idrace = st1.idrace)
	// )
	// select idrace, extract(epoch from laptime) laptime, lapnr,
	// 	(select sum(penaltyseconds) from comment where idrace = $1) penaltyseconds
	//  from result where laptime is not null and idrace = $1");

	  $laptimefetch = pg_prepare($dbconn, "laptimefetch", "with penaltiestodrive as (
select *, coalesce((select sum(laps)+1 from drive d2 where d1.idrace = d2.idrace and d2.drivenr<d1.drivenr), 1) fromdrive,
(select sum(laps) from drive d2 where d1.idrace = d2.idrace and d2.drivenr<=d1.drivenr) todrive
from drive d1 left join comment using (idrace, drivenr) order by idrace, drivenr)
select idrace, extract(epoch from laptime) laptime, lapnr, (select sum(penaltyseconds) from penaltiestodrive where penaltiestodrive.idrace = valid_laptimes.idrace and lapnr >= fromdrive and lapnr <= todrive) totalpenalty
from valid_laptimes where idrace = $1");
$result['debug2']=pg_last_error();

	$teamfetch = pg_execute($dbconn, "teamfetch", array($tier, $poule, $idchampionship));

	//resulting teams array
	$teams = array();
	while($row = pg_fetch_assoc($teamfetch)) {
		$team = $row;
		$team['races'] = array();
		$idteam = $row['idteam'];

		$result['debugracefetch'] = $tier.' '.$poule.' '.$idchampionship.' '.$idteam;

		//loop over each race
		$racefetchexec = pg_execute($dbconn, "racefetch", array($tier, $poule, $idchampionship, $idteam));

		while($racerow = pg_fetch_assoc($racefetchexec)) {
			$race = array();

			$race['idrace'] = $racerow['idrace'];
			$race['laptimes'] = array();
			$race['avglaptime'] = $racerow['avglaptime'];
			$race['sumlaptime'] = $racerow['sumlaptime'];

			//fetch the laptimes
			$laptimefetch = pg_execute($dbconn, "laptimefetch", array($race['idrace']));
			$result['debug1']=pg_last_error();
			while($laptimerow = pg_fetch_assoc($laptimefetch)) {
				$laptime = array();
				$laptime['laptime'] = $laptimerow['laptime'];
				$laptime['lapnr'] = $laptimerow['lapnr'];
				$laptime['totalpenalty'] = $laptimerow['totalpenalty'];
				$race['laptimes'][] = $laptime;
			}
			$team['races'][] = $race;
		}
		$teams[] = $team;
	}

	$result['teams'] = $teams;
	$result['ok'] = true;

	//print message
	$resultjson =  json_encode($result);
	echo $resultjson;
?>
