// const baseURL = "http://localhost:6001/service/map"
//const baseURL = "https://845e7e5cda79.ngrok.io/service/map"

const provGroup = "https://nepalmonitor.org/covid/returnAllData.php"
const distGroup = "https://nepalmonitor.org/covid/returnProvinceData.php"
const eachDist =  "https://nepalmonitor.org/covid/returnDistrictData.php"

// const provGroup = "http://localhost/mapsample/returnAllData.php"
// const distGroup = "http://localhost/mapsample/returnProvinceData.php"
// const eachDist = "http://localhost/mapsample/returnDistrictData.php"
var provData = [0, 20, 40, 60, 80, 100, 120, 150]

var distData = [0, 8, 15, 25, 35, 45, 55, 70]
var layData = provData;

function changeLegend() {
  $('#state-legend').empty();
  $('#state-legend').append(`
  <span><span style="background-color: #c7dfdd"></span>${layData[0]}</span>
  <span><span style="background-color: #78a5a2"></span>${layData[1]}</span>
  <span><span style="background-color: #679895"></span>${layData[2]}</span>
  <span><span style="background-color: #508a87"></span>${layData[3]}</span>
  <span><span style="background-color: #41837f"></span>${layData[4]}</span>
  <span><span style="background-color: #317b76"></span>${layData[5]}</span>
  <span><span style="background-color: #10524d"></span>${layData[6]}</span>
  <span><span style="background-color: #0a3d39"></span>${layData[7]}</span>`)
}

function loadDataChanges() {

  $('#loader').show();
  changeLegend()
  var colors = ['#eec524', '#24cfa2', '#e70c0c']


  if(typeof nepalGeo !== "undefined") {
    getProvData(nepalGeo)
    $('#loader').hide();

  } else {
    $.ajax({
      type: "GET",
      url: 'https://raw.githubusercontent.com/samit22/nepalgeo/master/province.geojson',
      dataType: "json",
      success: function (provData) {
        const dup = provData
        nepalGeo = dup
        getProvData(provData);
      }
    });
  }


  function getProvData(provData) {
    var type = $("#data-select").val()
    var startDate = $("#date-range").data('daterangepicker').startDate.format('YYYY-MM-DD');
    var endDate = $("#date-range").data('daterangepicker').endDate.format('YYYY-MM-DD');
    var url = provGroup + "?&start_date='" + startDate + "'&end_date='" + endDate + "'&type=" + type
    $.ajax({
      type: "GET",
      url: url,
      dataType: "json",
      success: function (provCases) {
        formatCases(provCases.results);
        map.addSource('prov-line-data', {
          type: 'geojson',
          data: provData,
        })
        map.addLayer({
          'id': 'prov-line-data',
          'type': 'line',
          'source': 'prov-line-data',
          'layout': {
            'visibility': 'visible'
          },
          'paint': {
            'line-color': '#ffffff',
            'line-width': 2
          }
        })
        $('#loader').slideUp()
      }
    })

    function formatCases(provCases) {
      var provCases = provCases;
      if(provCases.length === 0) {
        toastr.error("No data found! Change the date range")
        return
      }
      const formattedCases = convertToObject(provCases, "province")
      var results = provData.features
      var finalData = []
      for(var i = 0; i < results.length; i++) {
        var prov = results[i]
        var province_id = prov.properties.province_id
        var casData = formattedCases[prov.properties.province_id]
        var feature;
        if(casData) {
          var {
            count,
            province_name,
            violent,
            nonviolent
          } = casData

          feature = {
            province_name: province_name,
            count: count,
            type: type,
            province_id: province_id,
            violent: violent,
            non_violent: nonviolent,
          }
        } else {
          feature = {
            province_name: province_name,
            count: 0,
            type: type,
            province_id: province_id,
            violent: 0,
            non_violent: 0
          }
        }
        prov.properties = feature
        finalData.push(prov)

      }

      provCases.features = finalData

      map.addSource('prov-layer-data', {
        type: 'geojson',
        data: provData
      })

      map.addLayer({
        'id': 'prov-layer-data',
        'type': 'fill',
        'source': 'prov-layer-data',
        'layout': {
          'visibility': 'visible'
        },
        'paint': {
          'fill-color': [
            'interpolate',
            ['linear'],
            ['get', 'count'],
            layData[0],
            '#c7dfdd',
            layData[1],
            '#78a5a2',
            layData[2],
            '#679895',
            layData[3],
            '#508a87',
            layData[4],
            '#41837f',
            layData[5],
            '#317b76',
            layData[6],
            '#1e746e',
            layData[7],
            '#0a3d39'
          ],
          'fill-opacity': 0.75
        },

      })

    }


    var popup = new mapboxgl.Popup({
      closeButton: true,
      closeOnClick: true
    });

    map.on('click', 'prov-layer-data', function (e) {


      var data = e.features[0]
      var {
        province_name,
        count,
        type,
        violent,
        non_violent
      } = data.properties

      var message = type === 'all' ? `All incidents related to COVID-19: ${count}` : `Incidents related to ${dataMap[type]}: ${count}`


      const dt = `<div class="full-length" role="tooltip">
           <div class='popup-header'> ${province_name}</div>
           <hr>
           <div class="popup-body"> ${message}
           <hr>
           <div class="center-text"> Violent - ${violent} </div>
           <div class="center-text"> Other - ${non_violent} </div>
         </div>
         </div>`

      var coordinates = e.lngLat
      var description = dt
      while(Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
        coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
      }
      popup
        .setLngLat(coordinates)
        .setHTML(description)
        .addTo(map);
    });
    map.on('mouseover', 'prov-layer-data', function (e) {
      map.getCanvas().style.cursor = 'pointer';
    })

    map.on('mouseleave', 'prov-layer-data', function () {
      map.getCanvas().style.cursor = '';
    });
  }
}

