function changeDatePicker(startDate, endDate) {
    var type = $("#data-select").val();
  
    if(type === 'covid') {
        toastr.error("Covid data is not available in date ranges.")
        return
    }
    var selectedProv = $("#province-select").val()
    var selectedDist = $("#district-select").val()

    if(selectedProv != ""){
      var startDate = $("#date-range").data('daterangepicker').startDate.format('YYYY-MM-DD');
      var endDate = $("#date-range").data('daterangepicker').endDate.format('YYYY-MM-DD');
      $("#mapRight").load('allSideMapDataProvinceWise.php?province=' + value + '&start_date=' + startDate + '&end_date=' + endDate, {});
    } else {
     showAllSideMapDataDateWise();
    }

    if(typeof selectedDist != "undefined" && selectedDist != "" && selectedDist != null) {
        updateProvDistrictsLayer(selectedProv, startDate, endDate, type)
        var distDataURL = eachDist + "?start_date='" + startDate + "'&end_date='" + endDate + "'&type=" + type + "&district=" + parseInt(selectedDist)
        $.ajax({
            type: "GET",
            url: distDataURL,
            dataType: "json",
            success: function (districtCases) {
                modifyDistrictData(districtCases)
            }
        });

    } else if(typeof selectedProv != "undefined" && selectedProv != "" && selectedProv != null) {
        updateProvDistrictsLayer(selectedProv, startDate, endDate, type)

    } else {
        updateNepalGeo(startDate, endDate, type)
    }
}

function updateNepalGeo(startDate, endDate, type) {

    if(typeof nepalGeo === "undefined") {
        toastr.error("Something went wrong, please refresh the page!")
        return
    }

    var provData = nepalGeo
    var url = provGroup + "?start_date='" + startDate + "'&end_date='" + endDate + "'&type=" + type
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function (provCases) {
            formatCases(provCases.results);
        }
    })

    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
                }
            } else {
                feature = {
                    province_name: prov.properties.province_name,
                    count: 0,
                    type: type,
                    province_id: province_id,
                    violent: 0,
                    non_violent: 0,
                    color: "#fff",
                    description: "NA"
                }
            }


            prov.properties = feature
            finalData.push(prov)

        }
        provCases.features = finalData
       // map.getSource('prov-layer-data').setData(provData)
        if(type !== "all") {
            if(map.getSource('prov-layer-data-all')) {

                map.setLayoutProperty(
                    'prov-layer-data-all',
                    'visibility',
                    'none'
                );
            }
            map.getSource('prov-layer-data').setData(provData)
            map.setLayoutProperty(
                'prov-layer-data',
                'visibility',
                'visible'
            );
        } else {
            if(map.getSource('prov-layer-data')) {
                map.setLayoutProperty(
                    'prov-layer-data',
                    'visibility',
                    'none'
                );
            }
            map.getSource('prov-layer-data-all').setData(provData)
            map.setLayoutProperty(
                'prov-layer-data-all',
                'visibility',
                'visible'
            );
        }
    }

}
function updateProvDistrictsLayer(selectedProv, startDate, endDate, type) {
    var provID = parseInt(selectedProv)
    var distDataURL = distGroup + "?start_date='" + startDate + "'&end_date='" + endDate + "'&type=" + type + "&province=" + provID
    $.ajax({
        type: "GET",
        url: distDataURL,
        dataType: "json",
        success: function (districtData) {
            if(districtData.results.length === 0) {
                toastr.error("No new data change to different date range!")
                return
            }
            var formatDistData = convertToObject(districtData.results, "district")
            modifyProvDistLayer(formatDistData, provID, type)
            $('#loader').hide();
        }
    });
}

function modifyDistrictData(cases) {
    var data = cases.results
    if(data.lenght === 0) {
        toastr.error("No data found! Change the date range")
        return
    }
    var features = []
    for(var i in data) {
        let cs = data[i]
        var feature = {
            province_name: cs.province_name,
            distict: cs.district_name,
            type: dataMap[cs.type],
            description: cs.description,
            icon: 'harbor'
        }
        var geometry = {
            type: "Point",
            coordinates: [cs.lng, cs.lat]
        }
        features.push({
            type: "Feature", properties: feature, geometry: geometry
        })
    }
    const distCases = { type: "FeatureCollection", features: features }

    if(map.getSource('district-each')) {
        map.getSource('district-each').setData(distCases)
        return
    }
    map.addSource('district-each', {
        type: 'geojson',
        data: distCases,
    })
    map.addLayer({
        'id': 'district-each',
        'type': 'symbol',
        'source': 'district-each',
        'layout': {
            'visibility': 'visible',
            'icon-image': ['concat', ['get', 'icon'], '-15'],
            // get the title name from the source's "title" property
            'text-field': ['get', 'type'],
            'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
            'text-offset': [0, 0.6],
            'text-anchor': 'top'

        }
    })

}

function modifyProvDistLayer(districtData, provID, type) {
    var sourceID = "prov-layer-" + provID
    var cacheID = "prov" + provID + "Geo"
    var provData = cache[cacheID]
    if(isEmptyObject(provData)) {
        toastr.error("Something went wrong!! Refresh the page.")
        return
    }
    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_name,
                count: 0,
                type: type,
                violent: 0,
                non_violent: 0
            }
        }
        prov.properties = feature
        finalData.push(prov)
    }
    provData.features = finalData
    var source = map.getSource(sourceID)
    source.setData(provData)
}
