/*
 * movie play js
 */

function phook() {
    // Global markers in a map
    var map = L.map('map').setView([38.891, 139.824], 16); 
    var marker = L.marker().setLatLng(map.getCenter()).addTo(map);
    var timescale = 20;
    timescale = 1;
    // var videostart = new Date ('2019-07-29 09:32:35').getTime();
    var videostart = new Date ('2019-07-29T00:32:35Z').getTime();
    videostart += -81000;
    // alert(videostart);

    // MAP handling functions
    var basemaps = {
	'OpenStreetMap':
	{url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
	 attribution:
	 '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
	 maxZoom: 20, maxNativeZoom: 18},
	'国土地理院(標準)':
	{url: 'https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png',
	 attribution:
	 '&copy; <a href="https://maps.gsi.go.jp/development/ichiran.html">国土地理院</a>',
	 maxZoom: 20, maxNativeZoom: 18},
	'空中写真(国土地理院2007年-)':
	{url: 'https://cyberjapandata.gsi.go.jp/xyz/ort/{z}/{x}/{y}.jpg',
	 attribution:
	 '&copy; <a href="https://maps.gsi.go.jp/development/ichiran.html">国土地理院</a>',
	 maxZoom: 20, maxNativeZoom: 18},
    };
    var layers = {};
    for (let i in basemaps) {
	layers[i] = L.tileLayer(basemaps[i].url, basemaps[i]);
    }
    L.control.layers(layers, null).addTo(map);
    layers['OpenStreetMap'].addTo(map);
    // Load gpx
    var gpxgj, times, coords;
    // var gpx = omnivore.gpx("2019_07_29-Yawata.gpx");
    var pointnum=0;
    function setProperty(f, layer) { // カスタムレイヤ作成用の関数
	pointnum++;
    }
    var gpxURL = "2019_07_29-Yawata.gpx";
    gpxURL = "./getgpx.cgi?https://www.yatex.org/gitbucket/yuuji/debugging/raw/master/m3/2019_07_29-Yawata.gpx";
    var gpx = omnivore.gpx(gpxURL,
			   null,
			   L.geoJson(null, {
			       style: {color: "green", weight: 8},
			       onEachFeature: setProperty
			   }));
    var tmarray = [];
    gpx.on('ready', function() {
	var cons = document.getElementById('console');
	gpxgj  = this.toGeoJSON();
	times  = gpxgj.features[0].properties.coordTimes;
	coords = gpxgj.features[0].geometry.coordinates;
	// cons.textContent = times;
	// alert(times[0][0]);
	var d = new Date(Date.parse(times[0][0])),
	    start = d.getTime();	// Millisecond
	var ofs, t, tm;
	for (let i=0; i<times[0].length; i++) {
	    tm = times[0][i];
	    t = new Date(tm).getTime();
	    // ofs = t.getTime() - start;
	    tmarray.push([t, coords[0][i]]);
	}
	marker.setLatLng([38.94229999999999999999, 139.88699999999999999999]);
	map.setView(marker.getLatLng());
	alert(tmarray[0][0]+', -1='+tmarray[tmarray.length-1][0]+', vs='+videostart);
	//alert(new Date().getTimezoneOffset());
	cons.textContent = JSON.stringify(tmarray);
	// alert(d.toLocaleString());
	//      cons.textContent += JSON.stringify(gpxgj, null, " ");
    }).addTo(map);

    function seekGeom(t) {
	// Seek geom pos in tmarray{} by binary search
	var pseudot = t * 1000 * timescale + videostart;
	var left=0, right=tmarray.length-1, m;
	if (pseudot < tmarray[left][0] || pseudot > tmarray[right][0])
	    return null;
	console.log("IN="+pseudot);
	while (left<right) {
	    m = Math.floor((left+right)/2);
	    if (pseudot < tmarray[m][0])
		right = m-1;
	    else
		left = m+1;
	}
	console.log(m);
	return tmarray[m][1];
    }
    // Video Handling functions
    function dispTime(e) {
	var pt = document.getElementById("time");
	var geom, latlng;
	if (pt) {
	    pt.innerHTML = vi.currentTime;
	    geom = seekGeom(vi.currentTime);
	    console.log(JSON.stringify(geom));
	    latlng = L.latLng([geom[1], geom[0]])
	    marker.setLatLng(latlng);
	    map.setView(latlng);
	}
    }
    vi = document.getElementById("vid");
    vi.addEventListener('timeupdate', dispTime);
    function seekTime(latlng) {
	// Seek video time from tmarray
	var lat=latlng.lat, lng=latlng.lng, x, y, s, idx=0;
	var min = Math.pow(tmarray[0][1][0]-lat, 2) 
	    + Math.pow(tmarray[0][1][1]-lng, 2);
	var beg = new Date().getTime();
	for (let i=0; i<tmarray.length; i++) {
	    x = tmarray[i][1][0]; y=tmarray[i][1][1];
	    s = Math.pow(x-lng, 2) + Math.pow(y-lat, 2);
	    if (s < min) {
		idx = i;
		min=s;
	    }
	}
	console.log('lapse='+(new Date().getTime()-beg));
	return (idx>0) ?
	    (tmarray[idx][0] - videostart) / 1000 / timescale
	    :
	    null;
    }
    function setTime(e) {
	var input = document.getElementById('settime')
	if (e.type=='keypress' && e.key != 'Enter') return;
	if (input) {
	    vi.currentTime = input.value;;
	}
    }
    function clickToRewind(e) {
	var tm = seekTime(e.latlng);
	if (tm) {
	    vi.currentTime = tm;
	}
    }
    map.on("click", clickToRewind);
    document.getElementById("b").addEventListener('click', setTime);
    document.getElementById("settime").addEventListener('keypress', setTime);
}

window.onload = phook;
