var bolCaseData = {};
let bolPoly = {};
function loadBalMap() {
  $.ajax({
    type: 'GET',
    url: 'https://raw.githubusercontent.com/samit22/nepalgeo/master/pak/pak-all.geojson',
    dataType: 'json',
    success: function (balData) {
      const pakProv = balData.prov;
      const boldata = balData.balo_point;
      let bolPoly = balData.balo_poly;

      $.ajax({
        type: 'GET',
        url: 'https://dreamdevelopersnepal.com/sikharnet/apis/index.php/balochistan?type=all&district=all',
        dataType: 'json',
        success: function (data) {
          data.map(function (d) {
            bolCaseData[d.district_name] = d.count;
          });
          for (var i in bolPoly.features) {
            const prp = bolPoly.features[i].properties;
            bolPoly.features[i].properties['count'] = parseInt(
              bolCaseData[prp['ADM2_EN']] || 0,
            );
          }
          bolschMap.addSource('bol-map-pak-state', {
            type: 'geojson',
            data: pakProv,
          });

          bolschMap.addSource('bol-point-map', {
            type: 'geojson',
            data: boldata,
          });
          bolschMap.addSource('bol-map', {
            type: 'geojson',
            data: bolPoly,
          });

          bolschMap.addLayer({
            id: 'bol-pak-map-layer',
            type: 'fill',
            source: 'bol-map-pak-state',
            layout: {
              visibility: 'visible',
            },
            paint: {
              'fill-color': '#acaf3d',
              'fill-opacity': 0.9,
            },
          });

          bolschMap.addLayer({
            id: 'bol-pak-map-line',
            type: 'line',
            source: 'bol-map-pak-state',
            layout: {
              visibility: 'visible',
            },
            paint: {
              'line-color': '#ffffff',
              'line-width': 2,
            },
          });

          bolschMap.addLayer({
            id: 'bol-map-layer',
            type: 'fill',
            source: 'bol-map',
            layout: {
              visibility: 'visible',
            },
            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.9,
            },
          });

          bolschMap.addLayer({
            id: 'bol-map-line',
            type: 'line',
            source: 'bol-map',
            layout: {
              visibility: 'visible',
            },
            paint: {
              'line-color': '#ffffff',
              'line-width': 2,
            },
          });

          bolschMap.addLayer({
            id: 'bol-point-map',
            type: 'symbol',
            source: 'bol-point-map',
            layout: {
              'text-field': ['get', 'ADM2_EN'],
              'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
              'text-offset': [0, 0],
              'text-anchor': 'top',
              'text-size': 8,
            },
            filter: ['==', 'ADM1_EN', 'Balochistan'],
          });

          $('#bol-legend').empty();
          $('#bol-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>
        `);
        },
      });
    },
  });
}

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

function changeBolData() {
  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 selectedDist = $('#bol-dist-select').val();
  var source = bolschMap.getSource('bol-map-layer');
  if (
    typeof selectedDist == 'undefined' ||
    selectedDist == '' ||
    selectedDist == null
  ) {
    $.ajax({
      type: 'GET',
      url: `https://dreamdevelopersnepal.com/sikharnet/apis/index.php/balochistan?type=${type}&district=all&from=${startDate}&to=${endDate}`,
      dataType: 'json',
      success: function (data) {
        data.map(function (d) {
          bolCaseData[d.district_name] = d.count;
        });
        for (var i in bolPoly.features) {
          const prp = bolPoly.features[i].properties;
          bolPoly.features[i].properties['count'] = parseInt(
            bolCaseData[prp['ADM2_EN']] || 0,
          );
        }
        source.setData(bolCaseData);
      },
    });
  } else {
    console.log('district selected');
  }
}

function changeBolDistrict(sel) {
  const BolMapCoordinates = [
    [],
    ['Awaran', ['26.4749', '65.2679']],
    ['Barkhan', ['29.8995', '69.5246']],
    ['Bolan', ['29.2293', '67.6662']],
    ['Chagai', ['28.9804', '62.4504']],
    ['Dera Bugti', ['29.0352', '69.1596']],
    ['Gwada', ['25.131', '62.325']],
    ['Jaffarabad', ['28.3009', '68.1908']],
    ['Jhal Magsi', ['28.2816', '67.4576']],
    ['Kalat', ['29.0523', '66.5879']],
    ['Kech', ['26.1561', '63.0148']],
    ['Kharan', ['28.5855', '65.4163']],
    ['Khuzdar', ['27.8165', '66.6057']],
    ['Killa Abdullah', ['30.8055', '66.7129']],
    ['Killa Saifullah', ['30.7033', '68.3697']],
    ['Kohlui', ['29.2811', '75.5204']],
    ['Lasbe', ['25.87', '66.7129']],
    ['Loralai', ['30.3806', '68.5963']],
    ['Mastung', ['29.8825', '66.7844']],
    ['Musakhe', ['30.847', '69.955']],
    ['Nasirabad', ['28.2022', '67.9072']],
    ['Panjgur', ['26.9706', '64.0887']],
    ['Pishin', ['30.5897', '67.0107']],
    ['Quetta', ['30.179', '66.975']],
    ['Sibi', ['29.5532', '67.8808']],
    ['Zhob', ['31.3497', '69.4665']],
    ['Ziarat', ['30.3939', '67.7169']],
  ];
  var dist = sel.value;
  if (!dist) {
    bolPopup.remove();
    bolschMap.flyTo({
      center: {
        lat: 29.0523,
        lng: 66.5879,
      },
      speed: 0.4,
      zoom: 4.5,
    });

    return;
  }
  const districtSelected = BolMapCoordinates[dist][0];
  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');

  $.ajax({
    type: 'GET',
    url: `https://dreamdevelopersnepal.com/sikharnet/apis/index.php/balochistan?type=${type}&district=${districtSelected}&from=${startDate}&to=${endDate}`,
    dataType: 'json',
    success: function (data) {
      const gotData = data[0];

      bolschMap.flyTo({
        center: {
          lat: BolMapCoordinates[dist][1][0],
          lng: BolMapCoordinates[dist][1][1],
        },
        speed: 0.4,
        zoom: 7,
      });

      const dt = `<div class="full-length" role="tooltip">
      <div class='popup-header'> ${districtSelected}</div>
      <hr>
      <div class="center-text"> Description</div>
      <div class="center-text">  ${gotData.count} cases </div>
      </div>
      </div>`;

      var description = dt;
      bolPopup
        .setLngLat([
          BolMapCoordinates[dist][1][1],
          BolMapCoordinates[dist][1][0],
        ])
        .setHTML(description)
        .addTo(bolschMap);
    },
  });
}

