
use strict;
use warnings;

#接收參數與前置處理
my $id=$ARGV[0];
my $range=$ARGV[1];#模擬範圍座標
my $start=$ARGV[2];#起點座標 Like:121.21,45
$start=~s/,/ /g;#用空白取代","
my $end=$ARGV[3];#終點座標
$end=~s/,/ /g;#用空白取代","
my $way=$ARGV[4];#要過濾的way tag
$way=~s/=/ or highway=/g;#修改銜接字串
my $SWID;#起始街道ID
my $EWID;#終點街道ID

#預設檔案目錄以及檔名
my $sumoDir="/home/hsccl/sumo-0.23.0";#sumo目錄
my $scriptDir="/var/www/EMS_script";#script目錄
my $checkDir="/var/www/EMS_script/RouteCheck";#check目錄
my $map=$id . "-MAP.osm.xml";#下載圖檔的osm檔名
my $net=$id . "-MAP.net.xml";#輸出net檔名
my $flow=$id . "-FLOW.flow.xml";#輸出的flow檔名
my $route=$id . "-ROUTE.rou.xml";#輸出的route檔名

#下載圖檔
sub GetMap{
	#從OSM下載圖資
	system "wget", "-O", "$checkDir/$id-temp.osm", "http://overpass-api.de/api/map?bbox=$range";
	#system "wget", "-O", "$checkDir/$id-temp.osm", "http://api.openstreetmap.fr/api/0.6/map?bbox=$range";
	#system "wget", "-O", "$checkDir/temp.osm", "http://api.openstreetmap.org/api/0.6/map?bbox=$range";
	#圖資物件過濾
	system "$scriptDir/osmfilter $checkDir/$id-temp.osm --keep='highway=$way' --drop-version --drop-author -o=$checkDir/$map";
	#移除暫存圖檔
	system "rm","$checkDir/$id-temp.osm";
	#路網生成
	system "$sumoDir/bin/netconvert", "--osm-files", "$checkDir/$map", "-o", "$checkDir/$net","--geometry.remove","--roundabouts.guess","--ramps.guess","--junctions.join","--tls.discard-loaded","--no-internal-links","--remove-edges.isolated";
}

sub prepare{
	#下載圖檔並且確認是否正常轉換格式
	print "Download Map!\n";
	for (my $i = 0; $i < 10; $i++) {
		if (!(-e "$checkDir/$net")) {
			&GetMap;
			last;
		}
	}
	#下載失敗就結束程式
	if (!(-e "$checkDir/$net")) {
		print "Get map data from openstreetmap fail!\n";
		die;
	}else{
		print "Map download finish\n";
	}
	#起終點轉換街道ID
	#取得起點
	$SWID = readpipe "perl $scriptDir/calway.pl $checkDir/$map $start $checkDir/$net 500";
	#print "Start way ID:" . $SWID . "\n";
	#取得終點
	$EWID = readpipe "perl $scriptDir/calway.pl $checkDir/$map $end $checkDir/$net 500";
	#print "END way ID:" . $EWID . "\n";
}

#模擬參數設定與檔案產生
sub check{
	#設定EV
	#print "Create flow...\n";
	system  "echo '<flows><flow id=\"A\" from=\"$SWID\" to=\"$EWID\" begin=\"5\" end=\"300\" number=\"1\" color=\"0,0,1\" /></flows>' > $checkDir/$flow";
	#建立EV路徑
	#print "Create route...\n";
  my $result = `$sumoDir/bin/duarouter -n $checkDir/$net -f $checkDir/$flow -o $checkDir/$route 2>&1`;
	#printf $result."\n";
	if ($result =~ /Error/g) {
		print "Create route fail!!!\n";
	}else{
		print "Route Created!\n";
	}
	#移除檔案
	system "rm $checkDir/$id*";
}

&prepare;
&check;
