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

const provGroup = "https://nepalmonitor.org/civicspace/returnAllData.php"
const distGroup = "https://nepalmonitor.org/civicspace/returnProvinceData.php"
const eachDist  = "https://nepalmonitor.org/civicspace/returnDistrictData.php"
// const provGroup = "http://pos.a1pathshala.local/map-covid/phpmap2/returnAllData.php"
// const distGroup = "http://pos.a1pathshala.local/map-covid/phpmap2/returnProvinceData.php"
// const eachDist = "http://pos.a1pathshala.local/map-covid/phpmap2/returnDistrictData.php"

var provData = [0, 3,5, 8, 12, 18,25, 35];

var colorGrad = ["#e9cba1","#e3b778", "#d49d4e", "#d29339", "#d58b21", "#e48f14", "#e88f0e","#fa9502"]

var distData = [0, 3,5, 8, 12, 18,25, 35];

var layData = provData;

var provLegend = { "Closed": "#e71d26", "Obstructed": "#f6ab17", "Open": "#009d5c", "Narrowed": "#acaf3d", "Repressed": "#e46c16" };

function changeLegend(select) {
  $('#state-legend').empty();
  if(select === "prov") {
    var legendData = `<div class="legend-internal">`;
    for(const colorCode in provLegend) {
      var color = provLegend[colorCode];
      legendData += `<span style="font-size:14px; padding-left:14px;"><span style="background-color: ${color}"></span>${colorCode}</span>`
    }
    legendData += `</div>`
    $('#state-legend').append(legendData)
  }
  else {
    $('#state-legend').append(`
  <div class="legend-internal">
  <span><span style="background-color: ${colorGrad[0]}"></span>${layData[0]}</span>
  <span><span style="background-color: ${colorGrad[1]}"></span>${layData[1]}</span>
  <span><span style="background-color: ${colorGrad[2]}"></span>${layData[2]}</span>
  <span><span style="background-color: ${colorGrad[3]}"></span>${layData[3]}</span>
  <span><span style="background-color: ${colorGrad[4]}"></span>${layData[4]}</span>
  <span><span style="background-color: ${colorGrad[5]}"></span>${layData[5]}</span>
  <span><span style="background-color: ${colorGrad[6]}"></span>${layData[6]}</span>
  <span><span style="background-color: ${colorGrad[7]}"></span>${layData[7]}</span>
  </div>`)
  }
}

function loadDataChanges() {

  $('#loader').show();

  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);
        changeLegend("prov")
      }
    });
  }


  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,
            color,
            color_code,
            description
          } = casData

          feature = {
            province_name: province_name,
            count: count,
            type: type,
            province_id: province_id,
            violent: violent,
            non_violent: nonviolent,
            color: color,
            color_code: color_code,
            description: description,
          }
          provLegend[color_code] = color;
        } else {
          feature = {
            province_name: province_name,
            count: 0,
            type: type,
            province_id: province_id,
            violent: 0,
            non_violent: 0,
            color: "",
            color_code: "none",
            description: "NA",
          }
        }
        prov.properties = feature
        finalData.push(prov)

      }

      provCases.features = finalData

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

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

      map.addLayer({
        'id': 'prov-layer-data-all',
        'type': 'fill',
        'source': 'prov-layer-data-all',
        'layout': {
          'visibility': 'visible'
        },
        'paint': {
          'fill-color': ['get', 'color'],
          'fill-opacity': 1
        },
      });

      map.addLayer({
        'id': 'prov-layer-data',
        'type': 'fill',
        'source': 'prov-layer-data',
        'layout': {
          'visibility': 'none'
        },
        'paint': {
          'fill-color': [
            'interpolate',
            ['linear'],
            ['get', 'count'],
            layData[0],
            colorGrad[0],
            layData[1],
            colorGrad[1],
            layData[2],
            colorGrad[2],
            layData[3],
            colorGrad[3],
            layData[4],
            colorGrad[4],
            layData[5],
            colorGrad[5],
            layData[6],
            colorGrad[6],
            layData[7],
            colorGrad[7]
          ],
          '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,
        color,
      } = 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('click', 'prov-layer-data-all', function (e) {
      var data = e.features[0]
      var {
        province_name,
        count,
        type,
        violent,
        non_violent,
        description,
      } = 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="center-text"> Description</div>
           <div class="center-text">  ${description} </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 = '';
    });

    map.on('mouseover', 'prov-layer-data-all', function (e) {
      map.getCanvas().style.cursor = 'pointer';
    })

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

