<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>JogNoteのラップタイムをGarminConnectのtcxデータに挿入する</title>
</head>
<body>
  
<?php

// jsonファイルを置く場所が異なる場合は以下を編集
$jsonFiles = glob( dirname(__FILE__).'/JogNote/json/*.json' );
if (!empty($jsonFiles))
{
  foreach ($jsonFiles as $jsonFile)
  {
	$json = file_get_contents($jsonFile);
	$json = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
	$arr = json_decode($json,true);
	if ($arr === NULL) {die();}
?>
  
	<h1>【日付】<?php	echo $arr["note"]["date"];?></h1>
  　<p>天気:&nbsp;<?php	echo $arr["note"]["weather"];?></p>
  　<h2>ワークアウト</h2>
	<p>日記:&nbsp;<?php	echo $arr["note"]["diary"];?></p>
  	<?php
    foreach($arr["note"]["workouts"] as $_workouts)
	{
  	?>

  	<p>ワークアウトID:&nbsp;<?php	echo $_workouts["workout_id"];?></p>
	<p>ワークアウト名:&nbsp;<?php	echo $_workouts["name"];?></p>
  	<p><table border=1><tr><td>距離</td><td>タイム</td></tr>
  	<?php
      //各LAPデータを1行毎に出力
	  foreach($_workouts["laps"] as $_laps)
      {
  	?>
    	<tr><td><?php echo $_laps["meter"];?>&nbsp;</td>
    	<td><?php echo $_laps["sec"];?>&nbsp;</td></tr>
  	<?php
      }	// endof foreach $_laps
	?>
  
	</table></p>
	<p>GPSファイル名:<?php	echo $_workouts["route"];?></p>
  	<?php

    // 作業手順
    // JogNoteからエクスポートした.gpxファイルを一旦、GarminConnectにインポートして、
	// .tcx　ファイルでGarminConnectからエクスポートする。
    // GPSデータが無いものは対応していません。
    // JogNoteの.gpxからファイル名が変わっているので、名称を元の名称に戻す。具体的には、
    // JogNoteのjasonファイル内容の末尾に記載のファイル名から、拡張子のみ.tcxに変更したものにする。
    // 読み込みXMLファイルを置く場所が異なる場合も以下を編集
    // フォルダ内の全ファイルを一度に変換処理するので、負荷を考えオススメは20ファイルくらいまで。
	$read_tcx = dirname(__FILE__).'/JogNote/tcx/'.str_replace('.gpx','.tcx', $_workouts["route"]);

    // 書き出しXMLファイルを置く場所が異なる場合は以下を編集
    // 同じファイル名で保存するため、読み込みフォルダとは別の場所とすること
	$write_tcx = dirname(__FILE__).'/JogNote/tcx_w/'.str_replace('.gpx','.tcx', $_workouts["route"]);

    	// 読み込み用.tcxファイルが存在する場合のみ、処理する
		if( is_file($read_tcx) )
		{
			// XML形式のDOMオブジェクトに読み込み
      		$dom = new DOMDocument('1.0', 'UTF-8');
			$dom->preserveWhiteSpace = false;
			$dom->formatOutput = true;
			$dom->load($read_tcx);

          	// DomからActivityを抽出
        	$root       = $dom->getElementsByTagName("Activities")[0];
			$oActivity = $root->getElementsByTagName("Activity")[0];
          	$oActivity->setAttribute('Sport', 'Running');				// Activityの区分をRunningに変更

      		// GarminConnect上で1ラップとして存在したラップデータを読み込み 
			$oLap = $oActivity->getElementsByTagName("Lap")[0];
          
          	// LAPデータのポインタを初期化
          	$i_lap = 0;
          
          	// 総走行距離を記憶
          	$totalDistance = $oLap->getElementsByTagName('DistanceMeters')[0]->nodeValue;
          	// 総走行時間を記憶
          	$totalTime = $oLap->getElementsByTagName('TotalTimeSeconds')[0]->nodeValue;
          
	      	print("<p>走行距離:".$totalDistance."</p>");
          	print("<p>走行時間:".$totalTime."</p>");
	     	print("<p>最高速度:".$oLap->getElementsByTagName('MaximumSpeed')[0]->nodeValue."</p>");
                     	
          	$startTime = $oLap->getElementsByTagName('Track')[0]->getElementsByTagName('Trackpoint')[0]->getElementsByTagName('Time')[0]->nodeValue;
			$lapStartTime = $startTime;

            $cur_distance = $_workouts["laps"][$i_lap]["meter"];
           	$cur_dist_time = $_workouts["laps"][$i_lap]["sec"];
          	$cur_max_speed = $oLap->getElementsByTagName('MaximumSpeed')[0]->nodeValue;

          	foreach( $oLap->getElementsByTagName('Track')[0]->getElementsByTagName('Trackpoint') as $num_Trk => $oTrackpoint )
          	{
                          
             	if( $num_Trk == 0 || ( ( $_workouts["laps"][$i_lap-1]["meter"] <= $oTrackpoint->getElementsByTagName('DistanceMeters')[0]->nodeValue ) 
                   				&& ( $i_lap-1 < count( $_workouts["laps"]) ) ) )
              	{
                	print("----- LAP ------".($i_lap + 1)."</br>");

          			// DOMにLAPを追加
               		$newLap = $dom->createElement('Lap');
                	$oActivity->appendChild($newLap);
                	$newLap->setAttribute('StartTime', $lapStartTime);

                	$newdistance = $dom->createElement('DistanceMeters');
               		$newdistance->nodeValue = $cur_distance;
                	$newLap->appendChild($newdistance);
          			$newSeconds = $dom->createElement('TotalTimeSeconds');
                	$newLap->appendChild($newSeconds);
          			$newSpeed = $dom->createElement('MaximumSpeed');
                	$newLap->appendChild($newSpeed);
          			$newIntensity = $dom->createElement('Intensity');
                	$newLap->appendChild($newIntensity);
          			$newTriggerMethod = $dom->createElement('TriggerMethod');
                	$newLap->appendChild($newTriggerMethod);
          			$newTrack = $dom->createElement('Track');
                	$newLap->appendChild($newTrack);

                	$newLap->getElementsByTagName('DistanceMeters')[0]->nodeValue = $cur_distance;
                	$newLap->getElementsByTagName('TotalTimeSeconds')[0]->nodeValue = $cur_dist_time;
          			$newLap->getElementsByTagName('MaximumSpeed')[0]->nodeValue = $cur_max_speed;
          			$newLap->getElementsByTagName('Intensity')[0]->nodeValue = $oLap->getElementsByTagName('Intensity')[0]->nodeValue;
          			$newLap->getElementsByTagName('TriggerMethod')[0]->nodeValue = $oLap->getElementsByTagName('TriggerMethod')[0]->nodeValue;

                  	print("<p>区間距離:".$cur_distance."</p>");
            		print("<p>秒:".$cur_dist_time."</p>");
                  
                  	$lastTime = strtotime($oTrackpoint->getElementsByTagName('Time')[0]->nodeValue) ;
                 	print("<p>UnixTime:".$lastTime."</p>");
                
                	$last_distance = $_workouts["laps"][$i_lap]["meter"] - $last_distance;
               
                  	//--------------------------------------------
                  
				    print("走行距離:". $_workouts["laps"][$i_lap]["meter"]."</p>");
                  
                	$i_lap = $i_lap + 1;
                  	$lapStartTime = $oTrackpoint->getElementsByTagName('Time')[0]->nodeValue;

                  	if( !empty($_workouts["laps"][$i_lap]["meter"]) )
                    {	// 最終ラップを超えるまでは区間距離（今回ラップ距離－前回ラップ距離）
          				$cur_distance = $_workouts["laps"][$i_lap]["meter"] - $_workouts["laps"][$i_lap-1]["meter"];
                      	// 時間はラップ時間のまま代入
                      	$cur_dist_time = $_workouts["laps"][$i_lap]["sec"];
                    }
			          	// JogNoteには最終ラップ分が記録されていないので、最終GPSデータから計算する
                    else{  // 最終ラップを超えたら、総走行距離から引く
                        $cur_distance = $totalDistance - $_workouts["laps"][$i_lap-1]["meter"];
                      	// 時間はトータル時間から、開始時間～最終LAP開始時間　を差し引く
                      	$cur_dist_time = $totalTime - (strtotime($lapStartTime) - strtotime($startTime));
                    }
                  	$cur_max_speed = "";

                }	//end if
 
              	// GPSデータツリーを新しいLAPデータに１つずつ追加
            	$newLap->getElementsByTagName('Track')[0]->appendChild($oTrackpoint);

                print("-----------".$num_Trk."</br>");
              	//print($_workouts["laps"][$i_lap-1]["meter"]."</br>");	// debug
              	//print($oTrackpoint->getElementsByTagName('DistanceMeters')[0]->nodeValue."</br>");	// debug
                print("<p>TotalTimeSeconds:".$oTrackpoint->getElementsByTagName('Time')[0]->nodeValue."</p>");
              	print("<p>DistanceMeters:".$oTrackpoint->getElementsByTagName('DistanceMeters')[0]->nodeValue."</p>");
          	
            }	//end foreach 'Trackpoint'
          
            // GarminConnect上で1ラップとして存在したラップデータを消去  
          	$oActivity->removeChild($oActivity->getElementsByTagName("Lap")[0]);
		
		$dom->save($write_tcx);		
	
  	}	// end if $read_tcx exists
  }	//end foreach $_workouts
 }	// end foreach $jsonFiles
}	//end if $jsonFiles exists
?>
</body>
