import "whatwg-fetch";
require("../styles/index.scss");

function getUserPosition() {
    return new Promise(function(resolve, reject) {
        navigator.geolocation.getCurrentPosition(resolve, reject);
    });
}

var locs = [];
//var bearing = null;

if ('geolocation' in navigator)

fetch("data/cameras.json")
	.then(r => r.json())
	.then(function(cams) {
		navigator.geolocation.watchPosition(function(position) {
			let bearing = null;
			let min_dist = null;
			let nearest_cam = null;
			locs.unshift(position);

			// Which way am I going?
			if (locs.length >= 3) {
				locs = locs.slice(0,3);
				bearing =  Math.atan2(locs[2].coords.latitude - position.coords.latitude, locs[2].coords.longitude - position.coords.longitude);
			}
			for (let action of cams.actions) {
				let cam = action.dataItem;
				// throw out cams behind me here
				if (bearing != null) {
					let cam_angle =  Math.atan2(position.coords.latitude - cam.coordinates.lat, position.coords.longitude - cam.coordinates.lng);
					let diff = bearing - cam_angle;
					if (diff > Math.PI/4 || diff < Math.PI/-4) {
						continue;
					}
				}

				// This camera is still in front of me, is it the closest (so far)?
				let distance = Math.abs(position.coords.latitude - cam.coordinates.lat) + Math.abs(position.coords.longitude - cam.coordinates.lng);
				if (min_dist == null || min_dist > distance) {
					min_dist = distance;
					nearest_cam = cam;
				}
			}

			// Now, update the display
			document.getElementById("cam-title").textContent = nearest_cam.title;
			document.getElementById("cam-image").setAttribute("src", nearest_cam.thumbnailUrl);
			document.getElementById("cam-image").classList.remove("spin");
			document.getElementById("cam-stream-link").setAttribute("href", nearest_cam.rtspVideoUrl);
			document.getElementById("stream-button-section").classList.remove("u-hide");
		});
	});
