$(document).ready(function () {
    var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
        trgt = 'https://bipad.gov.np/api/v1/covid19-case?expand=district&limit=-1';
    var url = proxyUrl + trgt;
    $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function (districtData) {
            // formatDistrictData(districtData);
        }
    });

    function formatDistrictData(dd) {

        function formatGeo(district, cs, latlng) {
            var recovered, active, deaths = 0;
            if(cs === "death") {
                deaths = 1
            } else if(cs === "recovered") {
                recovered = 1
            } else {
                active = 1
            }
            return {
                "type": "Feature",
                "properties": {
                    "id": district,
                    "district": district,
                    "recovered": recovered,
                    "active": active,
                    "deaths": deaths,
                },
                "geometry": {
                    "type": "Point",
                    "coordinates": latlng
                }
            }
        }

        // FOrmat end
        let districtData = dd.results;
        var res = []
        for(var i = 0; i < districtData.length; i++) {
            let d = districtData[i]
            let district = d.district
            let currentState = d.currentState
            let latlng = district.centroid.coordinates;

            res.push(formatGeo(district.title, currentState, latlng))
        }
        var data = {
            "type": "FeatureCollection",
            "features": res
        }
        var active = ['==', ['get', 'active'], 1];
        var recovered = ['==', ['get', 'recovered'], 1];
        var deaths = ['==', ['get', 'deaths'], 1];

        var colors = ['#eec524', '#24cfa2', '#e70c0c']
        map.addSource('districtData', {
            type: 'geojson',
            data: data,
            cluster: true,
            clusterRadius: 5,
            clusterProperties: {
                // keep separate counts for each magnitude category in a cluster
                'active': ['+', ['case', active, 1, 0]],
                'recovered': ['+', ['case', recovered, 1, 0]],
                'deaths': ['+', ['case', deaths, 1, 0]],
                'district': ["string", ['get', "district"]]
            }
        });

        map.addLayer({
            'id': 'district_circle',
            'type': 'circle',
            'source': 'districtData',
            'layout': {
                'visibility': 'none',
            },
            'paint': {
                'circle-color': [
                    'case',
                    active,
                    colors[0],
                    recovered,
                    colors[1],
                    colors[2]
                ],
                'circle-opacity': 0.6,
                'circle-radius': 12
            }
        })

        map.addLayer({
            'id': 'district_label',
            'type': 'symbol',
            'source': 'districtData',
            'layout': {
                'visibility': 'none'
            },
        });

        map.on('click', 'district_circle', function (e) {
            var coordinates = e.features[0].geometry.coordinates.slice();
            var prpts = e.features[0].properties || {}
            var active = prpts.active || 0
            var deaths = prpts.deaths || 0
            var recovered = prpts.recovered || 0
            var district = prpts.district || ""
            var positive = active + deaths + recovered
            var recovery_rate = roundOff(recovered / positive * 100)
            var mortality_rate = roundOff(deaths / positive * 100)
            var coordinates = e.lngLat
            while(Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
            }

            const dt = `<div class="full-length" role="tooltip">
           <div class='popup-header'> District: ${district}</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>`

            new mapboxgl.Popup()
                .setLngLat(coordinates)
                .setHTML(dt)
                .addTo(map);
        });
        $("#district").removeAttr("disabled");
        $("#spinner").css("display", "none")

    }

})
