<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>geolocation tracker test</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="/apple-touch-icon.png">
        <!-- Place favicon.ico in the root directory -->

    </head>
    <body>
        <!--[if lt IE 8]>
            <p class="browserupgrade">
            You are using an <strong>outdated</strong> browser. Please
            <a href="http://browsehappy.com/">upgrade your browser</a> to improve
            your experience.
            </p>
        <![endif]-->

        <button id = "initialise">Start Tracking</button><br/>
        <p id = "status"></p>
        <a id = "map-link" target="_blank"></a>

        <p>
            Latitude: <span id="latitude"></span><br>
            Longitude: <span id="longitude"></span><br>
            Altitude: <span id="altitude"></span><br>
            Accuracy: <span id="accuracy"></span><br>
            Speed: <span id="speed"></span><br>
            Angle: <span id="angle"></span><br>
        </p>

        <input id="note" placeholder="enter note here">
        <button id="submit-note">Submit</button>

        <p>
            <button id="download">Download Log</button>
            <button id="reset">Reset History</button>
        </p>
        <p id="error"></p>
    </body>
    <script>

     /* TODO:
     /  - how to push things to rocket? (probably just http post for now …)
     /  - how to rate-limit new positions (either count dates, or option in geolocation?)
     /  - how to get closest point on path?
     */

     let lat = document.getElementById("latitude");
     let long = document.getElementById("longitude");
     let speed = document.getElementById("speed");
     let acc = document.getElementById("accuracy");
     let angle = document.getElementById("angle");
     let alt = document.getElementById("altitude");

     let status = document.querySelector('#status');
     let mapLink = document.querySelector('#map-link');

     function resetDisplay () {
         lat.innerText = "-";
         long.innerText = "-";
         speed.innerText = "-";
         acc.innerText = "-";
         angle.innerText = "-";
         alt.innerText = "-";
     }

     function init() {

         mapLink.href = '';
         mapLink.textContent = '';

         resetDisplay();

         if(!navigator.geolocation) {
             status.textContent = 'Error: Geolocation API is not supported!';
         } else {
             status.textContent = 'Initialising …';
             trackPosition();
         }

     }
     var errcount = 1;
     var geolog = [];

     function trackPosition() {
         function success(position) {
             const latitude  = position.coords.latitude;
             const longitude = position.coords.longitude;
             errcount = 0;

             status.textContent = '';
             mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
             mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;

             lat.innerText = position.coords.latitude;
             long.innerText = position.coords.longitude;
             alt.innerText = position.coords.altitude;
             acc.innerText = position.coords.accuracy;
             speed.innerText = position.coords.speed;
             angle.innerText = position.coords.heading;

             document.getElementById("error").innerText = JSON.stringify(position.coords);

             let datapoint = {
                 timestamp: new Date().toISOString(),
                 data: {
                     latitude: position.coords.latitude,
                     longitude: position.coords.longitude,
                     altitude: position.coords.altitude,
                     accuracy: position.coords.accuracy,
                     altitudeAccuracy: position.coords.altitudeAccuracy,
                     heading: position.coords.heading,
                     speed: position.coords.speed
                 }
             };

             geolog.push(datapoint);
             fetch(
                 "https://ilztal.live/geoloc/push",
                 { method: "POST", body: JSON.stringify(datapoint)}
             ).then(() => console.log("pushed position"))
              .catch(e => console.log("some error: ", e))
         }

         function error() {
             status.textContent = "("+errcount+") Error: Getting Location failed, retrying …";
             resetDisplay();
             errcount += 1;
             setTimeout(trackPosition, 3000);
         }

         navigator.geolocation.watchPosition(success, error);
     }

     function downloadHistory () {
         let json = JSON.stringify(geolog);
         let a = document.createElement("a");
         console.log("attempting download!", geolog);
         a.setAttribute("href", "data:text/plain;charset=utf-8," + encodeURIComponent(json));
         a.setAttribute("download","history.json");
         document.body.appendChild(a);
         a.click();
         document.body.removeChild(a);
     }

     document.getElementById("initialise").addEventListener('click', init);

     document.getElementById("submit-note").onclick = (a) => {
         let input = document.getElementById("note");
         let text = input.value;
         console.log("submitting note:", text);
         geolog.push(text);
         fetch("https://ilztal.live/geoloc/push",
               {method:"POST", body: JSON.stringify({
                   //ty: "note",
                   timestamp: new Date().toISOString(),
                   data: text
               })}
         ).then(() => input.value = "")
          .catch(e => {
              document.getElementById("error").innerText = "error:" + e;
              console.log("error occurred");
          });
     };

     document.getElementById("download").onclick = (a) => downloadHistory();

     document.getElementById("reset").onclick = (a) => geolog = [];

    </script>


    </body>
</html>