#!/usr/bin/php
<?
require_once 'settings/settings.php';

$Quest = new DataBase();
$Events = array();
$Commune = array();
$CommuneScores = array();

// Retrieve events info
$EventsHeader = "INSERT INTO event (id, ads_id_event, event_date, lat, lon, depth, zone_name, n_quests, mag_pref_type, mag_pref_value, epicenter) VALUES ";
$EventsBody = array();

$Quest->ExecMySQLiQuery("SELECT * from event WHERE ads_id_event <> 0 order by event_date;");
while($data = $Quest->GetNext()){
	$EventsBody[] = sprintf("(%d, %d, '%s', %f, %f, %f, '%s', %d, '%s', %f, 'SRID=4326;POINT(%f %f)')",
		$data['id'],
		$data['ads_id_event'],
		$data['event_date'],
		$data['lat'],
		$data['lon'],
		$data['depth'],
		preg_replace("/'/", "''", ($data['zone_name'])),
		$data['n_quests'],
		$data['mag_pref_type'],
		$data['mag_pref_value'],
		$data['lon'],
		$data['lat']
	);
}
echo $EventsHeader . "\n" . implode(",\n", $EventsBody) . ";\n";
unset($EventsHeader);
unset($EventsBody);
unset($data);

$CommuneHeader = 'INSERT INTO commune (id, name, istat_code, lat, lon, municipality) VALUES ';
$CommuneBody = array();

$Quest->ExecMySQLiQuery("SELECT * from commune WHERE version = 2 ;");
while($data = $Quest->GetNext()){
	$CommuneBody[] = sprintf("(%d, '%s', '%s', %f, %f, 'SRID=4326;POINT(%f %f)')",
		$data['id'],
		preg_replace("/'/", "''", ($data['name'])),
		$data['istat_code'],
		$data['lat'],
		$data['lon'],
		$data['lon'],
		$data['lat']
	);
}
echo $CommuneHeader .  "\n" . implode(",\n", $CommuneBody)  . ";\n";
unset($CommuneHeader);
unset($CommuneBody);
unset($data);

$CommuneScoresHeader = 'INSERT INTO commune_scores (id_event,id_commune,intensity_type,intensity_value, n_valid_quests) VALUES ';
$CommuneScoresBody = array();

$Quest->ExecMySQLiQuery("SELECT cs.* from commune_scores cs inner join event e on (cs.id_quake = e.id) inner join commune c on (cs.id_commune = c.id) WHERE attenuated = FALSE ;");
while($data = $Quest->GetNext()){
	$CommuneScoresBody[] = sprintf("(%d, %d, %d, %f, %d)",
			$data['id_quake'],
			$data['id_commune'],
			$data['intensity_type'],
			$data['intensity_value'],
			$data['n_valid_quests']
		);
}
echo $CommuneScoresHeader . "\n" . implode(",\n", $CommuneScoresBody) . ";\n";
unset($CommuneScoresHeader);
unset($CommuneScoresBody);
unset($data);

$Quest->CloseConnection();

?>
