import * as messaging from "messaging";
import { geolocation } from "geolocation";

function setWeatherPosition(curLat, curLong){
  const weatherURL ='https://pro.openweathermap.org/data/2.5/weather?lat='+ curLat + '&lon=' + curLong + '&appid=808d3f40ec186cba8cfd12456ebca02e&units=imperial';  
  fetch(weatherURL)
.then(response => response.json())
.then(data => {
   var weather = {
          forecast: data.weather[0].main,
          icon: data.weather[0].icon,
          temperature: data["main"]["temp"],
          humidity: data["main"]["humidity"]
        }
   //console.log(data);
        // Send the weather data to the device
        returnWeatherData(weather);
})


 .catch(function (err) {
    console.error(`Error fetching weather: ${err}`);
  });
}

function returnWeatherData(data) {
  if (messaging.peerSocket.readyState === messaging.peerSocket.OPEN) {
    messaging.peerSocket.send(data);
  } else {
    console.error("Error: Connection is not open");
  }
}

messaging.peerSocket.addEventListener("message", (evt) => {
  if (evt.data && evt.data.command === "weather") {
    geolocation.getCurrentPosition(function(position) {
   var curLat = position.coords.latitude;
   var curLong = position.coords.longitude;
    setWeatherPosition(curLat, curLong);
})
  }
});

messaging.peerSocket.addEventListener("error", (err) => {
  console.error(`Connection error: ${err.code} - ${err.message}`);
});


