window.onload = function() {
    fetch('/map_view')
        .then(response => response.json())
        .then(data => {
            mapboxgl.accessToken = data.mapbox_access_token;           
       
            var map1 = new mapboxgl.Map({
                container: 'map_view_bg',
                style: 'mapbox://styles/mapbox/dark-v10',
                center: [data.device_data[0].lon, data.device_data[0].lat],
                zoom: 5
            });
            map1.addControl(new mapboxgl.NavigationControl());
            addMarkers(map1, data.device_data);
            
           
            var map2 = new mapboxgl.Map({
                container: 'mapTop',
                style: 'mapbox://styles/mapbox/dark-v10',
                center: [data.device_data[0].lon, data.device_data[0].lat],
                zoom: 2
            });
            map2.addControl(new mapboxgl.NavigationControl());
            addMarkers(map2, data.device_data);

            // Default selection
            var defaultDeviceID = window.localStorage.getItem("deviceId")
            if(defaultDeviceID){
                window.localStorage.setItem("deviceId",defaultDeviceID)
            }else{
                defaultDeviceID = "xAq9W1PO5rmAuuQ"
                window.localStorage.setItem("deviceId",defaultDeviceID)
            }

            var defaultDevice = data.device_data.find(device => device.device_id === defaultDeviceID);
            if (defaultDevice) {
                var defaultMarker = new mapboxgl.Marker()
                    .setLngLat([defaultDevice.lon, defaultDevice.lat])
                    .setPopup(new mapboxgl.Popup().setHTML(`<h3>${defaultDevice.name}</h3>`))
                    // .addTo(map0);

                defaultMarker.getElement().click();
                updateDeviceData(defaultDevice); 
            }
        })
}

function addMarkers(map, device_data) {
    device_data.forEach(device => {
        var marker = new mapboxgl.Marker()
            .setLngLat([device.lon, device.lat])
            .setPopup(new mapboxgl.Popup().setHTML(`<h3>${device.name}</h3>`))
            .addTo(map);
        
        marker.getElement().addEventListener('click', function() {

            updateDeviceData(device);
            // console.log(device.device_id,"device id");
            window.localStorage.setItem("deviceId",device.device_id)
            // console.log(window.localStorage.getItem("deviceId"));

        });
    });
}

function updateDeviceData(device) {
    document.querySelector('.ipNumber').innerText = `${device.pod}`;
    let date = new Date().toLocaleString('en-US', { timeZone: device.timezone });
    document.querySelector('#timezone_date').innerText = `${date}`;
    
    // Check if the timezone is Singapore
    if (device.timezone === "Singapore") {
        document.querySelector('#singaporetext').style.display = "none"; // Show
    } else {
        document.querySelector('#singaporetext').style.display = "none"; // Hide
    }
}
