/* 朝日中央地区: LatLng(38.671707, 139.795534), LatLng(38.572461, 139.880335) */
document.addEventListener("DOMContentLoaded", () => {
    var bounds = [[38.672624, 139.768734], [38.562711, 139.914402]];
    var komisen = [[38.613491, 139.834304],[38.609797, 139.838132]];
    var center = [38.617121, 139.8417];
    var inizoom = 13;
    var infobox = document.getElementById("info");
    var mymapL = L.map("leftmap").setView(center, inizoom);
    L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
	attribution:
	'&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(mymapL);
    mymapL.on('contextmenu', (e) => {
	// alert(e.latlng);
	let b=mymapL.getBounds(),
	    b1=b.getNorthWest(), b2=b.getSouthEast();
	infobox.innerText = `${e.latlng}, bound=${b1}, ${b2}`;
    });
    var mymapR = L.map("rightmap").setView(center, inizoom);
    // LatLng(38.903357, 139.813385), LatLng(38.878639, 139.834585)
    var leftBounds = mymapL.getBounds();
    // L.imageOverlay("image/asahi.png",bounds).addTo(mymapR);
    // L.imageOverlay("image/asahi-chuo2.jpg", leftBounds).addTo(mymapR);
    mymapR.setMaxBounds(bounds);
    function syncmap(srcmap, destmap) { // mapをlatLng中心にする
	var z=srcmap.getZoom(), c=srcmap.getCenter()
	destmap.setZoom(z); destmap.setView(c);
	//infobox.innerText = `Center: ${c}, zm=${z}`;
    }
    
    var gpsmarker = L.marker(mymapL.getCenter()).addTo(mymapL);
    gpsmarker.bindPopup("START").openPopup();
    var geticon = L.icon({iconUrl:"image/Yellow.png",iconSize:[40,41],iconAnchor:[10,41],popupAnchor:[3,-40]});
    var gpsmarkerR = L.marker(mymapR.getCenter()).addTo(mymapR);

    var nTrial = 10;
    var watchId = null;

    let titen =[];
    let marker =[];
    let judge = [];
    let comment =[];
    var point = [],pos = 0;
    var tmp = [];
    var info = [];
    var stampimg=[];
    const endpoint = "https://script.google.com/macros/s/AKfycbzA9iZotNFTQ7xpYWUbQdOhXwU-_pIFS5lqOIDZ9GLlQyAqIUTCLi-78EPKUEdkdG-0/exec";
    
    function putValues(row){
	for (let key of Object.keys(row)){
	}
    }
    function init(){
	fetch(endpoint).
	    then((response)=>response.json())
	    .then(data =>{
		const csv = data;
		for (let x of csv){
		    putValues(x);
		    let p = L.latLng(x.lat,x.lng);
		    titen.push(p);
		    comment.push(x.comment);
		    info.push(x.info);
		    stampimg.push(x.stamp);
		    marker.push(L.marker(p).bindPopup(x.name).addTo(mymapR));
		    var elem = document.createElement('img');
		    elem.id = `image${pos}`;
		    elem.src = 'image/img.png';
		    var stamp = document.getElementById('stamp');
		    stamp.appendChild(elem);
		    pos += 1;
		}
	    });;
    }
    init();
    
    
    function stopGPS() {
	console.log("watchId="+watchId);
	if (watchId != null) {
	    navigator.geolocation.clearWatch(watchId);
	    gpsmarker.setPopupContent("停止");
	}
	watchId = null;
    }
    function tryWatchGPS() {
	stopGPS();
	watchId = navigator.geolocation.watchPosition(
	    onSuccess,onError,{
		maximumAge: 0, timeout: 3000, enableHighAccuracy: true});
    }

    function onSuccess(pos) {
	var latlng = L.latLng([pos.coords.latitude, pos.coords.longitude]);
	mymapL.panTo(latlng);
	console.log(latlng);
	gpsmarker.setLatLng(latlng).setPopupContent(
	    "lat="+latlng.lat+",lng="+latlng.lng+"です"
	).openPopup();
	gpsmarkerR.setLatLng(latlng);
	judgeimage(komisen);
	for (var i in titen){
	    if (latlng.distanceTo(titen[i]) < 50){
		if (!judge[i]){
		    judge[i] = true;
		    alert("スタンプゲット!!!");
		    let img = document.getElementById(`image${i}`);
		    img.src = stampimg[i];
		    marker[i].setIcon(geticon).setPopupContent(comment[i]);
		    
		}
	    }
	}
    }
    function onError(err) {
	restN = "あと"+(--nTrial)+"回試行します";
	gpsmarker.setPopupContent("補足失敗:"+restN).openPopup();
	if (nTrial <= 0) {
	    navigator.geolocation.clearWatch(watchId);
	}
    }

    
    mymapL.options.singleClickTimeout = 250;
    mymapL.on('singleclick', function(e) {
	if (true) {
	    latlng = L.latLng(e.latlng);
	    gpsmarker.setLatLng(e.latlng).setPopupContent(
		"lat="+latlng.lat+",lng="+latlng.lng+""
	    ).openPopup();
	    gpsmarkerR.setLatLng(e.latlng);
	}
	for (var a in komisen){
	    if (latlng.distanceTo(komisen[a]) < 200){
		L.imageOverlay("image/commcen.png", komisen).addTo(mymapR);
	    }
	}
	for (var i in titen) {
	    if (latlng.distanceTo(titen[i]) < 50) {
		if (!judge[i]){
		    judge[i] = true;
		    let img = document.getElementById(`image${i}`);
		    img.src = "image/hanyo.png";
		    alert("スタンプゲット!!!");
		    marker[i].setIcon(geticon).setPopupContent(comment[i]);
		}
	    }
	}
	function clickListener(e) {
	    for (var a in info){
		let target = document.getElementById(`image${i}`);
		let el = document.getElementById(info);
	    target.addEventListener('click', () => {
		el.innerText = info[a];
	    },false)
	    }
	}
    })
    
    
    mymapL.on('zoomend', (e) => {syncmap(mymapL, mymapR);});
    mymapL.on('moveend', (e) => {syncmap(mymapL, mymapR);});
    document.getElementById("start").addEventListener("click", tryWatchGPS);
    document.getElementById("stop").addEventListener("click", stopGPS);
});
