
function changeProvince(sel) {
  layData = distData;
  changeLegend()
  const prov = {
    1: {
      name: "Province 1",
      coordinates: [87.27197088279, 27.21052319087246],
      id: 1,
      code: 'p1',
      zoom: 7.4
    },
    2: {
      name: "Province 2",
      coordinates: [85.68968070300077, 26.930519228980092],
      id: 2,
      code: 'p2',
      zoom: 7.5
    },
    3: {
      name: "Bagmati",
      coordinates: [85.47056392270287, 27.67865196906648],
      id: 3,
      code: 'p3',
      zoom: 7.5
    },
    4: {
      name: "Gandaki",
      coordinates: [84.04977237130528, 28.40906158952393],
      id: 4,
      code: 'p4',
      zoom: 7.4
    },
    5: {
      name: "Province 5",
      coordinates: [82.68667353277905, 28.051445416166732],
      id: 5,
      code: 'p5',
      zoom: 7.5,
    },
    6: {
      name: "Karnali",
      coordinates: [82.28232937335169,
        29.253508516077503],
      id: 6,
      code: 'p7',
      zoom: 7.1
    },

    7: {
      name: "Sudurpashchimin",
      coordinates: [80.94032627817676, 29.324895476256362],
      id: 7,
      code: 'p7',
      zoom: 7.2
    }
  }
  var value = sel.value;

  if(map.getSource('district-each')) {
    map.removeLayer('district-each')
    map.removeSource('district-each')
  }

  var type = $("#data-select").val()
  if(type === "covid") {
    removeProvCovidSources()
    handleCovidDataChange(value);
  } else {
    if(value != "") {
      $("#barChartData").load('showBarDataProvinceWise.php?code=' + type + '&value=' + value, {});
      $("#mapRight").load('allSideMapDataProvinceWise.php?province=' + value, {});
      //$("#suicideData").load('showSuicideData.php?geography=' + value, {});
    } else {
      //alert(type);
      //$("#barChartData").load('showBarData.php?code=' + type, {});
      layData = provData;
      changeLegend()
      //alert ("not occupied");
      showBarData(type);
      ///showSideMapData();
      //showSuicideData('all');
    }
    //  $("#barChartData").load('showBarDataProvinceWise.php?code='+type+"&value="+value, { });
    removeProvDataSources()
    handleDataChange(value, type);
  }

  function handleCovidDataChange(value) {
    let latlng = [84.1240, 28.3949]
    var zoom = 6
    if(value) {
      $('#loader').show();
      var provLayer = map.getLayoutProperty('prov-layer-covid', 'visibility');
      if(provLayer === 'visible') {
        map.setLayoutProperty("prov-layer-covid", 'visibility', 'none');
        map.setLayoutProperty("prov-line-covid", 'visibility', 'none');
      }

      var data = provincesMap[value]
      latlng = data.coordinates
      zoom = data.zoom
      const provDistricts = findProvDistricts(value)
      setDistrictValue(provDistricts)
      getProvDistrictCovid(value, provDistricts)
    } else {
      var provLayer = map.getLayoutProperty('prov-layer-covid', 'visibility');
      if(provLayer === 'none') {
        map.setLayoutProperty("prov-layer-covid", 'visibility', 'visible');
        map.setLayoutProperty("prov-line-covid", 'visibility', 'visible');
      }
      $('#district-select').selectpicker('deselectAll');
      $('#district-select').selectpicker('refresh');
      $('#district-select').prop('disabled', true);
    }

    map.flyTo({
      center: {
        lat: latlng[1],
        lng: latlng[0]
      },
      speed: 0.4,
      zoom: zoom
    });

  }

  function handleDataChange(value, type) {
    let latlng = [84.1240, 28.3949]
    var zoom = 6
    if(value) {
      $('#loader').show();
      var provLayer = map.getLayoutProperty('prov-layer-data', 'visibility');
      if(provLayer === 'visible') {
        map.setLayoutProperty("prov-layer-data", 'visibility', 'none');
        map.setLayoutProperty("prov-line-data", 'visibility', 'none');
      }

      var data = provincesMap[value]
      latlng = data.coordinates
      zoom = data.zoom
      const provDistricts = findProvDistricts(value)
      setDistrictValue(provDistricts)
      getProvDistrictData(value, provDistricts, type)
    } else {
      var provLayer = map.getLayoutProperty('prov-layer-data', 'visibility');
      if(provLayer === 'none') {
        map.setLayoutProperty("prov-layer-data", 'visibility', 'visible');
        map.setLayoutProperty("prov-line-data", 'visibility', 'visible');
      }
      dataSelectChange()

      $('#district-select').selectpicker('deselectAll');
      $('#district-select').val([]);
      $('#district-select').prop('disabled', 'disabled');
      $('#district-select').selectpicker('refresh');
    }

    map.flyTo({
      center: {
        lat: latlng[1],
        lng: latlng[0]
      },
      speed: 0.4,
      zoom: zoom
    });
  }
}


function getProvDistrictData(prov, provDistricts, type) {
  const provUrl = "https://raw.githubusercontent.com/samit22/nepalgeo/master/govmap/Province-" + prov + ".geojson"
  $.ajax({
    type: "GET",
    url: provUrl,
    dataType: "json",
    success: function (provLevelGeo) {
      let source = 'prov-line-' + prov
      let id = 'prov-line-' + prov
      let layID = 'prov-layer-' + prov
      var cacheID = "prov" + prov + "Geo"
      cache[cacheID] = provLevelGeo

      provLevelDataData(provLevelGeo, prov, type);
      map.addSource(source, {
        type: 'geojson',
        data: provLevelGeo,
      })
      map.addLayer({
        'id': id,
        'type': 'line',
        'source': source,
        'layout': {
          'visibility': 'visible'
        },
        'paint': {
          'line-color': '#1e3ef7',
          'line-width': 2.5
        }
      })

    }
  });

  function provLevelDataData(provLevelGeo, provID, type) {
    var startDate = $("#date-range").data('daterangepicker').startDate.format('YYYY-MM-DD');
    var endDate = $("#date-range").data('daterangepicker').endDate.format('YYYY-MM-DD');
    var distDataURL = distGroup + "?start_date='" + startDate + "'&end_date='" + endDate + "'&type=" + type + "&province=" + provID
    $.ajax({
      type: "GET",
      url: distDataURL,
      dataType: "json",
      success: function (districtData) {
        var formatDistData = convertToObject(districtData.results, "district")
        addDataDistrictLayer(formatDistData, provLevelGeo, provID)
        $('#loader').hide();
      }
    });
  }

  function addDataDistrictLayer(districtData, provLevelGeo, provID) {
    let provData = provLevelGeo
    var results = provData.features
    var finalData = []
    for(var i = 0; i < results.length; i++) {
      var prov = results[i]
      var casData = districtData[prov.id]
      var feature;
      if(casData) {
        var {
          district_name,
          count,
          violent,
          nonviolent
        } = casData

        feature = {
          district_name: district_name || "",
          count: count,
          type: type,
          violent: violent,
          non_violent: nonviolent,
        }
      } else {
        feature = {
          district_name: prov.properties.district_title || "",
          count: 0,
          type: type,
          violent: 0,
          non_violent: 0
        }
      }
      prov.properties = feature
      finalData.push(prov)
    }
    provLevelGeo.features = finalData

    let layID = 'prov-layer-' + provID

    map.addSource(layID, {
      type: 'geojson',
      data: provData
    })

    map.addLayer({
      'id': layID,
      'type': 'fill',
      'source': layID,
      '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', layID, function (e) {

      var data = e.features[0]
      var {
        district_name,
        type,
        count,
        violent,
        non_violent
      } = data.properties
      var message;
      if (count == 0){
        message = type === 'all' ? "No Covid-19 realated incidents" : `No incidents related to ${dataMap[type]}`
      } else {
        message = type === 'all' ? `All incidents realated to COVID-19: ${count} <div class="center-text"> <hr>Violent - ${violent} </div>
           <div class="center-text"> Other - ${non_violent} </div>` : ` Incidents related to ${dataMap[type]}: ${count}
        <div class="center-text"> <hr> Violent - ${violent} </div>
        <div class="center-text"> Other - ${non_violent} </div>`
      }

      const dt = `<div class="full-length" role="tooltip">
           <div class='popup-header'> ${district_name}</div>
           <hr>
           <div class="popup-body"> ${message}
         </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', layID, function (e) {
      map.getCanvas().style.cursor = 'pointer';
    })

    map.on('mouseleave', layID, function () {
      map.getCanvas().style.cursor = '';
    });

  }
}

function getProvDistrictCovid(prov, provDistricts) {
  const provUrl = "https://raw.githubusercontent.com/samit22/nepalgeo/master/govmap/Province-" + prov + ".geojson"
  $.ajax({
    type: "GET",
    url: provUrl,
    dataType: "json",
    success: function (provLevelGeo) {
      let source = 'prov-line-covid-' + prov
      let id = 'prov-line-covid-' + prov
      map.addSource(source, {
        type: 'geojson',
        data: provLevelGeo,
      })
      map.addLayer({
        'id': id,
        'type': 'line',
        'source': source,
        'layout': {
          'visibility': 'visible'
        },
        'paint': {
          'line-color': '#909eee',
          'line-width': 2
        }
      })
      provLevelDataCovid(provLevelGeo, prov, provDistricts);

    }
  });

  function provLevelDataCovid(provLevelGeo, provID, provDistricts) {
    var proxyUrl = 'https://cors-anywhere.herokuapp.com/'
    var trgt = 'https://bipad.gov.np/api/v1/covid19-case?province=' + provID + '&limit=-1';
    $.ajax({
      type: "GET",
      url: proxyUrl + trgt,
      dataType: "json",
      success: function (rawProvCases) {
        let districtData = getDistrictCases(rawProvCases)
        addCovidDistrictLayer(districtData, provLevelGeo, provID)
        $('#loader').hide();
      }
    });
  }
  function addCovidDistrictLayer(districtData, provLevelGeo, provID) {
    let provData = provLevelGeo
    var results = provData.features
    var finalData = []
    for(var i = 0; i < results.length; i++) {
      var prov = results[i]
      var casData = districtData[prov.id]
      var feature;
      if(casData) {
        var {
          total_positive,
          total_death,
          district_name,
          total_recovered
        } = casData

        feature = {
          district_name: district_name,
          positive: total_positive,
          recovered: total_recovered,
          deaths: total_death,
          active: total_positive - total_recovered - total_death,
          mortality_rate: roundOff((total_death / total_positive) * 100) || 0,
          recovery_rate: roundOff((total_recovered / total_positive) * 100) || 0,
        }
      } else {
        feature = {
          district_name: prov.properties.district_title,
          positive: 0,
          recovered: 0,
          deaths: 0,
          active: 0,
          mortality_rate: 0,
          recovery_rate: 0,
        }
      }
      prov.properties = feature
      finalData.push(prov)
    }
    provLevelGeo.features = finalData

    let layID = 'prov-layer-covid-' + provID

    map.addSource(layID, {
      type: 'geojson',
      data: provData
    })

    map.addLayer({
      'id': layID,
      'type': 'fill',
      'source': layID,
      'layout': {
        'visibility': 'visible'
      },
      'paint': {
        'fill-color': [
          'interpolate',
          ['linear'],
          ['get', 'positive'],
          0,
          '#c7dfdd',
          5,
          '#78a5a2',
          10,
          '#679895',
          20,
          '#508a87',
          50,
          '#41837f',
          100,
          '#317b76',
          500,
          '#1e746e',
          1000,
          '#0a3d39'
        ],
        'fill-opacity': 0.75
      },

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

    map.on('click', layID, function (e) {
      var data = e.features[0]
      var {
        district_name,
        positive,
        active,
        deaths,
        recovered,
        recovery_rate,
        mortality_rate,
      } = data.properties

      const dt = `<div class="full-length" role="tooltip">
           <div class='popup-header'> ${district_name}</div>
           <hr>
           <div class="popup-body"> Cases: ${positive
        } <br> Active: ${active
        } <span class="percentage"> (${roundOff(active / positive * 100)}%) </span> <br> Recovered: ${recovered
        } <br> Deaths: ${deaths
        }
             <div class="recovered-color"> Recovery Rate: ${recovery_rate}% </div>
           </div>
           <div class="deaths-color"> Mortality Rate: ${mortality_rate}% </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', layID, function () {
      map.getCanvas().style.cursor = 'pointer';
    })

    map.on('mouseleave', layID, function () {
      map.getCanvas().style.cursor = '';
    });

    // end
  }

}

function setDistrictValue(provDistricts) {
  $('#district-select').find('option')
    .remove()
    .end()

  for(let c in provDistricts) {
    let dist = provDistricts[c];
    let value = { value: dist.id, text: dist.title };
    $('#district-select').prop('disabled', false);
    $('#district-select').append($('<option>', value));
    $('#district-select').selectpicker('refresh');
  }

}

function getDistrictCases(districtRawData) {
  let district = convertToObject(districts, "id")
  const res = districtRawData.results
  // for(var i in res) {
  // }

  var totals = res.reduce(function (r, o) {
    let data = r[o.district]
    if(data) {
      data.total_positive += 1
      if(o.currentState == "active") {
        data.total_active += 1
      } else if(o.currentState == "recovered") {
        data.total_recovered += 1
      } else {
        data.totaldeaths += 1
      }
    } else {
      let active = 0, recovered = 0, deaths = 0;
      if(o.currentState == "active") {
        active = 1
      } else if(o.currentState == "recovered") {
        recovered = 1
      } else {
        deaths = 1
      }
      r[o.district] = { total_positive: 1, total_active: active, total_recovered: recovered, total_death: deaths, district_name: district[o.district].title, details: district[o.district] }
    }
    return r;
  }, {});
  return totals
}

function removeProvCovidSources() {
  let sources = map.getStyle().sources
  for(var i = 1; i <= 7; i++) {
    var sourceID = "prov-line-covid-" + i
    var layer = "prov-layer-covid-" + i
    let thisSource = sources[sourceID]
    if(thisSource) {
      map.removeLayer(sourceID)
      map.removeLayer(layer)
      map.removeSource(sourceID)
      map.removeSource(layer)
    }
  }
}

function removeProvDataSources() {
  let sources = map.getStyle().sources
  for(var i = 1; i <= 7; i++) {
    var sourceID = "prov-line-" + i
    var layer = "prov-layer-" + i
    let thisSource = sources[sourceID]
    if(thisSource) {
      map.removeLayer(sourceID)
      map.removeLayer(layer)
      map.removeSource(sourceID)
      map.removeSource(layer)
    }
  }
}
