<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Basic Page Needs
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta charset="utf-8" />
  <title>
    <%= it.siteTitel %>
  </title>
  <meta name="description" content="<%= it.desc %>" />
  <meta name="author" content="<%= it.author %>" />

  <!-- Mobile Specific Metas
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <!-- CSS
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="stylesheet" href="css/normalize.css" />
  <link rel="stylesheet" href="css/barebones.css" />
  <link rel="stylesheet" href="css/skeleton-legacy.css" />
  <link rel="stylesheet" href="css/mainMap.css" />

  <!-- Favicon
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <link rel="icon" type="image/png" href="images/favicon-16.png" />

  <script async defer src="/js/site.js"></script>
  <script src="https://kit.fontawesome.com/<%= it.fontawesomeKey %>.js" crossorigin="anonymous"></script>

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css"
    integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
    crossorigin="" />

  <!-- Make sure you put this AFTER Leaflet's CSS -->
  <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"
    integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
    crossorigin=""></script>

  <script src="vendor/jquery/jquery-3.2.1.min.js"></script>

  <link rel="stylesheet" href="./leafletCluster/dist/MarkerCluster.css" />
  <link rel="stylesheet" href="./leafletCluster/dist/MarkerCluster.Default.css" />

  <script src="./leafletCluster/dist/leaflet.markercluster.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>

  <script src="./js/site.js"></script>
</head>

<body>
  <!-- Primary Page Layout
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <div id="overlay">
    <div id="text">
      We've detected that there is a draft in your current session. Do you want to restore it?<br>
      <button class="button-primary" onclick="restoreFunc()">Yes, restore it</button>
      <button onclick="noRestore()">No, don't restore it</button>
    </div>
  </div>
  <div style="margin: 0px">
    <div class="map" id="map"></div>

    <div class="inspector" id="inspector">
      <br /><br /><br /><br />
      <center>
        <h3>Create a new elevator</h3>

      </center>
      <step id="step1">
        <h5>1. Add a location</h5>
        <p>Click anywhere on the map to create a pin. You can also use direct input to add cordinates.</p>
        <label for="lat">Latlitude: </label><input type="number" name="lat" id="lat">
        <label for="lng">Longlitude: </label><input type="number" name="lng" id="lng">
        <br>
        <button onclick="nextDialogePage()" class="button-primary">Next step <i class="fas fa-arrow-right"></i></button>
      </step>
      <step id="step2" style="display: none;">
        <h5>2. Add general information about the elevator</h5>
        <p>You may add images in the last step. Now please enter general information about the elevator.</p>
        <label for="type">Elevator type:</label>

        <select name="type" id="type">
          <option value="0">Hydraulic</option>
          <option value="1">Wiredriven, motor in shaft</option>
          <option value="2">Wiredriven, motor in motorroom</option>
          <option value="3">Unknown</option>
        </select>
        <label for="visit">Visitabilty:</label>
        <select name="visit" id="visit">
          <option value="1">Public</option>
          <option value="2">On private property</option>
          <option value="3">Public but locked</option>
        </select>
        <label for="pepl">Max. passangers:</label>
        <input type="number" step="1" min="1" id="pepl" name="pepl" value=4>
        <label for="weig">Max. Weight (kg):</label>
        <input type="number" step="1" min="1" id="weig" name="weig" value=0>
        <label for="flor">Amount of Floors:</label>
        <input type="number" step="1" min="1" id="flor" name="flor" value=0>


        <br>
        <button onclick="prevPage()">Go back one step <i class="fas fa-arrow-left"></i></button>
        <button onclick="nextDialogePage()" class="button-primary">Next step <i class="fas fa-arrow-right"></i></button>
      </step>
      <step id="step3" style="display: none;">
        <h5>3. Add a description</h5>
        <p>Add a description to the elevator. You may not use this field for advertisment.</p>
        <textarea id="description"></textarea>
        <label for="manuf">Manufacturer: </label>
        <input type="text" id="manuf" name="manuf">
        <label for="model">Modell: </label>
        <input type="text" id="model" name="model">
        <br>
        <button onclick="prevPage()">Go back one step <i class="fas fa-arrow-left"></i></button>
        <button onclick="nextDialogePage()" class="button-primary">Next step <i class="fas fa-arrow-right"></i></button>
      </step>
      <step id="step4" style="display: none;">
        <h5>4. Add images</h5>
        <p>This is the last step. You can now add images. <b>Make sure no personal information is visibel in the
            image.</b></p>
        <input type="file" id="myFile" name="myFile" multiple>

        <br>
        <button onclick="prevPage()">Go back one step <i class="fas fa-arrow-left"></i></button>
        <button onclick="nextDialogePage()" class="button-primary">Next step <i class="fas fa-arrow-right"></i></button>
      </step>
      <step class="missingAlert" id="missingAlert" style="display: none;">
        <i class="fas fa-exclamation-triangle"></i> There are some empty fields. Please check the previous pages for
        empty fields!<br>
        <button onclick="prevPage()">Go back one step <i class="fas fa-arrow-left"></i></button>
      </step>
      <step id="step5" style="display: none;">
        <h5>5. Ready</h5>
        <p>Are you sure you want to submit this elevator?</p>
        <button style="background-color: greenyellow;" onclick="submit()"><i class="fas fa-check"></i></button>

        <button onclick="currentPage = 3; updateDialog()">Go back one step <i class="fas fa-arrow-left"></i></button>
      </step>
      <step id="step6" style="display: none;">
        <h5>6. Saving</h5>
        <br><br>
        <center>
          <div class="lds-ripple">
            <div></div>
            <div></div>
          </div>
          <div style="display: none; color: grey;" id="imageUploadInfo">
            Uploading image -/-
          </div>
        </center>
      </step>
    </div>
  </div>

  <aside>
    <i style="color: black; cursor: pointer" class="fas fa-map-marker-alt" onclick="home()"></i>
  </aside>
  <script type="text/javascript">

    function noRestore() {
      off();
      Cookies.remove("tempStore")
    }

    function restoreFunc() {
      try {
        dataBlock = JSON.parse(dataBlock)
        document.getElementById("lat").value = dataBlock["lat"]
        document.getElementById("lng").value = dataBlock["lng"]
        document.getElementById("type").value = dataBlock["type"]
        document.getElementById("visit").value = dataBlock["visit"]
        document.getElementById("pepl").value = dataBlock["pepl"]
        document.getElementById("weig").value = dataBlock["weig"]
        document.getElementById("manuf").value = dataBlock["manuf"]
        document.getElementById("model").value = dataBlock["model"]
        document.getElementById("flor").value = dataBlock["flor"]
        document.getElementById("description").value = dataBlock["description"]
      } catch (ex) {
        dataBlock = {}
      }
      off()
    }

    dataBlock = Cookies.get("tempStore");
    if (dataBlock == undefined) {
      dataBlock = {};
    } else {
      on()
    }

    var currentPage = 0;
    function saveValues() {
      dataBlock["lat"] = document.getElementById("lat").value
      dataBlock["lng"] = document.getElementById("lng").value
      dataBlock["type"] = document.getElementById("type").value
      dataBlock["visit"] = document.getElementById("visit").value
      dataBlock["pepl"] = document.getElementById("pepl").value
      dataBlock["weig"] = document.getElementById("weig").value
      dataBlock["manuf"] = document.getElementById("manuf").value
      dataBlock["model"] = document.getElementById("model").value
      dataBlock["flor"] = document.getElementById("flor").value
      dataBlock["description"] = document.getElementById("description").value
      Cookies.set('tempStore', JSON.stringify(dataBlock))
    }

    function submit() {
      currentPage = 6;
      updateDialog()
      saveValues()
      const options = {
        method: 'POST',
        body: JSON.stringify({})
      };

      fetch('/api/saveNewElevatorMeta', options)
        .then(response => response.json())
        .then(response => {
          console.warn("!!!!!!!!!!!!", response)
          document.getElementById("imageUploadInfo").style.display = 'block';
          var filesToSend = $('#myFile').prop('files').length;
          var i = 0;
          while (i < filesToSend) {
            document.getElementById("imageUploadInfo").innerHTML = "Uploading image " + String(i) + "/" + String(filesToSend)
            console.log("Files left to send: ", filesToSend - i)
            var file_data = $('#myFile').prop('files')[i];
            var form_data = new FormData();
            form_data.append('file', file_data);

            console.log(file_data)
            if (String(file_data.type).includes("image/")) {
              $.ajax({
                url: '/api/uploadImage?id=' + response.id,
                dataType: 'json',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function (data) {
                  alert(data);
                }
              });
            } else {
              console.log("Skipping nonimage file")
            }
            i++;
          }
        });








    }
    function updateDialog() {
      if (currentPage == 0) {
        document.getElementById("step1").style.display = 'block';
        document.getElementById("step2").style.display = 'none';
        document.getElementById("step3").style.display = 'none';
        document.getElementById("step4").style.display = 'none';
      }
      if (currentPage == 1) {
        document.getElementById("step1").style.display = 'none';
        document.getElementById("step2").style.display = 'block';
        document.getElementById("step3").style.display = 'none';
        document.getElementById("step4").style.display = 'none';
      }
      if (currentPage == 2) {
        document.getElementById("step1").style.display = 'none';
        document.getElementById("step2").style.display = 'none';
        document.getElementById("step3").style.display = 'block';
        document.getElementById("step4").style.display = 'none';
      }
      if (currentPage == 3) {
        document.getElementById("step1").style.display = 'none';
        document.getElementById("step2").style.display = 'none';
        document.getElementById("step3").style.display = 'none';
        document.getElementById("step4").style.display = 'block';
        document.getElementById("step5").style.display = 'none';
        document.getElementById("missingAlert").style.display = 'none';
      }
      if (currentPage == 4) {
        document.getElementById("step1").style.display = 'none';
        document.getElementById("step2").style.display = 'none';
        document.getElementById("step3").style.display = 'none';
        document.getElementById("step4").style.display = 'none';

        containsEmpt = false;
        for (const [key, value] of Object.entries(dataBlock)) {
          if (value == "" || value == undefined) {
            console.log("hi")
            console.log(key, value)
            containsEmpt = true;
            document.getElementById("missingAlert").style.display = 'block';
          }
        }
        if (containsEmpt == false) {
          document.getElementById("missingAlert").style.display = 'none';
          currentPage = 5;
        }
        console.log(containsEmpt);
      }
      if (currentPage == 5) {
        document.getElementById("step1").style.display = 'none';
        document.getElementById("step2").style.display = 'none';
        document.getElementById("step3").style.display = 'none';
        document.getElementById("step4").style.display = 'none';
        document.getElementById("step5").style.display = 'block';
        document.getElementById("missingAlert").style.display = 'none';
      }
      if (currentPage == 6) {
        document.getElementById("step1").style.display = 'none';
        document.getElementById("step2").style.display = 'none';
        document.getElementById("step3").style.display = 'none';
        document.getElementById("step4").style.display = 'none';
        document.getElementById("step5").style.display = 'none';
        document.getElementById("step6").style.display = 'block';
        document.getElementById("missingAlert").style.display = 'none';
      }
      saveValues();
      console.log(dataBlock)

    }
    function nextDialogePage() {
      currentPage++;
      updateDialog();
    }
    function prevPage() {
      currentPage--;
      updateDialog();
    }

  </script>

  <!-- End Document
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
  <script type="text/javascript">

    var latElm = document.getElementById("lat");
    var lngElm = document.getElementById("lng");

    latElm.addEventListener('input', function (evt) {
      markers.clearLayers();
      console.log(evt.target.value)
      const lat = evt.target.value;
      const lng = lngElm.value;
      var marker = new theMarker([lat, lng])
      //marker.addTo(mymap)
      markers.addLayer(marker);
      markers.addTo(mymap);
    });

    lngElm.addEventListener('input', function (evt) {
      markers.clearLayers();
      console.log(evt.target.value)
      const lat = latElm.value;
      const lng = evt.target.value;
      var marker = new theMarker([lat, lng])
      //marker.addTo(mymap)
      markers.addLayer(marker);
      markers.addTo(mymap);
    });

    var amountOfImages = 0;
    var markers = L.markerClusterGroup();
    slideIndex = 1;

    var mymap = L.map("map").setView([51.505, -0.09], 50);

    L.tileLayer(
      "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=<%= it.mapboxAccessToken %>",
      {
        attribution:
          'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        maxZoom: 18,
        id: "mapbox/streets-v11",
        tileSize: 512,
        zoomOffset: -1,
        accessToken: "<%= it.mapboxAccessToken %>",
      }
    ).addTo(mymap);

    theMarker = L.Marker.extend({
      options: {
        id: "-1",
      },
    });

    function showPosition(position) {
      console.log(position.coords);

      mymap.setView(
        new L.LatLng(position.coords.latitude, position.coords.longitude),
        10
      );
      // mymap.setView(new L.LatLng(10.737, -73.923), 8);
    }

    home()

    mymap.on('click', function (e) {
      markers.clearLayers();
      var coord = e.latlng;
      var lat = coord.lat;
      var lng = coord.lng;
      var marker = new theMarker([lat, lng])
      //marker.addTo(mymap)
      markers.addLayer(marker);
      markers.addTo(mymap);
      document.getElementById("lat").value = lat
      document.getElementById("lng").value = lng
      console.log("You clicked the map at latitude: " + lat + " and longitude: " + lng);
    });

    function addPin(item, index) {
      var marker = new theMarker([item.lat, item.lng], {
        id: item.id,
      }).on("click", onClick);
      // var marker = new L.Marker()
      //marker.addTo(mymap).on('click', onClick);
      markers.on("clusterclick", function (a) {
        //alert('cluster ' + a.layer.getAllChildMarkers().length);
      });
      markers.addLayer(marker);
    }

  </script>
</body>

</html>