const locURL = "locGet.php";
  
const locParag = document.getElementById('locParag');
const jumboParag = document.getElementById('jumboParag');
let userName = localStorage.getItem('smartCamUser');
let userPass = localStorage.getItem('smartCamPass');


//checks to see if user is loged in
if (userName == null && userPass == null) {
    jumboParag.textContent = "You are not loged in ";
    //if it's loged in, user can initiate stream
} else {
    jumboParag.textContent = userName + " | LOCATION Page";
    
    //leafletjs.com using mapbox api to create a map inside the mapid DIV
    function drawMap(lat, long) {
        
        //******Using public TOKEN because other ones not working*****
        
        var mymap = L.map('mapid').setView([lat, long], 15);
        L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
            maxZoom: 18,
            id: 'mapbox/streets-v11',
            tileSize: 512,
            zoomOffset: -1,
            accessToken: 'pk.eyJ1IjoiY2F0YXN0ZWYiLCJhIjoiY2thNXUxYXRmMDBrdzJycG5wYjNmbHBqYSJ9.CD8UIKc0Be8w9AdLQIa0Qg'
        }).addTo(mymap);
        var marker = L.marker([lat, long]).addTo(mymap);
    
    
        /* token 1, old not working any more
        sk.eyJ1IjoiY2F0YXN0ZWYiLCJhIjoiY2thNXZscGQ0MDEwaDJ3bGVydWxmbXFwNSJ9.Pl1XorVcdpM2mRM6XOhtkw
        */
        
        /* token 2, new created but not working
        sk.eyJ1IjoiY2F0YXN0ZWYiLCJhIjoiY2t2bHM0aWk2NzUzNDJucXcxaDZ4YWZnNiJ9.RTZDyYwG7sajy8ATsmtvsQ*/
       
        
        //code from mapbox api , works but style needs work
        /*        
        mapboxgl.accessToken = 'pk.eyJ1IjoiY2F0YXN0ZWYiLCJhIjoiY2thNXUxYXRmMDBrdzJycG5wYjNmbHBqYSJ9.CD8UIKc0Be8w9AdLQIa0Qg';
        const map = new mapboxgl.Map({
        container: 'map', // container ID
        style: 'mapbox://styles/mapbox/streets-v11', // style URL
        center: [long, lat], // starting position [lng, lat]
        zoom: 15 // starting zoom
        }); */
    }
    
    //put username inside form for php call
    let locForm = new FormData();
    locForm.append('userName', userName);

    //calls php and gets latitude and longitude for the user mobile device
    async function getLotationData(locForm) {
        const response = await fetch(locURL, {
            method: 'POST',
            body: locForm
        });
        const coordStr = await response.text();
        let coordArr = coordStr.split('-');
        let latitude = parseFloat(coordArr[0]);
        let longitude = parseFloat(coordArr[1]);
        
        locParag.textContent = "Latitude: " + latitude + " | Longitude: " + longitude;
        drawMap(latitude, longitude);
    }

    getLotationData(locForm);
}

