Code viewer for World: Weather Prep
//AI Weather by Meteosource api link: https://rapidapi.com/MeteosourceWeather/api/ai-weather-by-meteosource
//TrueWay Directions by TrueWay Team api link: https://rapidapi.com/trueway/api/trueway-directions2

arr = []; //will store the latitudes and longitudes of the origin and destination
from = "";  //stores the origin name
to = "";    //stores the destiniation name
const present = new Date(); //current time
departHour = present.getHours();

async function getPlace() { //invoked by button from home() function and destination() function, fetches details of places queried
        queriedPlace = $("#query").val();
        queriedHour = $("#time").val();
        if (parseInt(queriedHour) > 0 && parseInt(queriedHour) < 24) {
            departHour = parseInt(queriedHour);
        }
        const url = `https://ai-weather-by-meteosource.p.rapidapi.com/find_places?text=${queriedPlace}&language=en`;
        
        // MH edit
        console.log ( url );

        const options = {
	    method: 'GET',
	    headers: {
		    'X-RapidAPI-Key': '6f9a7275a0msh307bfbf770ae5aap199127jsn14c0d405bc2e',
		    'X-RapidAPI-Host': 'ai-weather-by-meteosource.p.rapidapi.com'
	    }
    };

    try {
	    const response = await fetch(url, options);
	    const result = await response.json();
	    
	    // MH edit
	    console.log(result);
	    
	    findLongLat(result);
    } catch (error) {
	    console.error(error);
    }
}

function findLongLat(data) {    //finds longitude and latitude from a place details json
    found = false;
    //arr = [];
    for (var i = 0; i < data.length; i++){
        //document.write("<br><br>array index: " + i);
        var obj = data[i];
        if (obj["country"] == "Republic of Ireland") { 
            if (from == "") {
                from = obj["name"];
            }
            else {
                to = obj["name"];
            }
            floatLat = parseFloat(obj["lat"].slice(0, -1));
            floatLon = parseFloat(obj["lon"].slice(0, -1));
            if (obj["lat"].slice(-1) == "S") {
                floatLat = floatLat * -1;
            }
            if (obj["lon"].slice(-1) == "W") {
                floatLon = floatLon * -1;
            }
            arr.push(floatLat);
            arr.push(floatLon);
            found = true;
            break;
        }
    }
    if (found && arr.length == 4) {
        //getWeather(arr);
        calcRoute(arr);
    }
    else if (found) {
        destination();
    }
}

async function getWeather(data, hour) { //fetch weather details, hour parameter is just there for passing it to the next function
        const url = `https://ai-weather-by-meteosource.p.rapidapi.com/hourly?lat=${data[0]}&lon=${data[1]}&timezone=auto&language=en&units=metric`;
 
         // MH edit
        console.log ( url );

       const options = {
	    method: 'GET',
	    headers: {
		    'X-RapidAPI-Key': '6f9a7275a0msh307bfbf770ae5aap199127jsn14c0d405bc2e',
		    'X-RapidAPI-Host': 'ai-weather-by-meteosource.p.rapidapi.com'
	    }
    };

    try {
	    const response = await fetch(url, options);
	    result = await response.json();
	    //places.push(result);
	    //addResult(result);
	    
	    // MH edit
        console.log(result);
        
        displayWeather(result, hour);
    } catch (error) {
	    console.error(error);
    }
}

function displayWeather(data, hour) {   //displays weather details, does not display all weather details, just the ones people would frequently look at the most
    var hourly = data["hourly"]["data"];    //this is an array within a json object, within the main json object from the parameter
    document.write("<br> - " + "timezone" + ": " + data["timezone"]);
    document.write("<br> - " + "units" + ": " + data["units"] + "<br>");
    
    //for (var i = 0; i < hourly.length; i++) {
        //console.log(i);
        var obj = hourly[hour]; //within that array, are various json objects, each index is represented by the hour i.e. index 0 == current time, index 1 == roughly 1 hour from now, etc
        document.write("<br> - " + "date" + ": " + obj["date"]);
        document.write("<br> - " + "temperature" + ": " + obj["temperature"] + " degrees celsius");
        document.write("<br> - " + "feels like" + ": " + obj["feels_like"] + " degrees celsius");
        document.write("<br> - " + "weather summary" + ": " + obj["weather"]);
        document.write("<br> - " + "humidity" + ": " + obj["humidity"] + "%");
        document.write("<br> - " + "Wind Speed" + ": " + obj["wind"]["speed"] + "km/h");
        document.write("<br> - " + "precipitation probability" + ": " + obj["probability"]["precipitation"] + "%");
        document.write("<br>");
    //}
}

async function calcRoute(data) {    //uses a different api for calculating the driving route of places, this is to grab the estimated duration of driving
        const url = `https://trueway-directions2.p.rapidapi.com/FindDrivingRoute?stops=${data[0]}%2C%20${data[1]}%3B${data[2]}%2C%20${data[3]}`;
  
        // MH edit
        console.log ( url );

       const options = {
    	method: 'GET',
    	headers: {
    		'X-RapidAPI-Key': '6f9a7275a0msh307bfbf770ae5aap199127jsn14c0d405bc2e',
    		'X-RapidAPI-Host': 'trueway-directions2.p.rapidapi.com'
    	}
};

    try {
    	const response = await fetch(url, options);
    	const result = await response.json();
    	
        // MH edit
        console.log(result);
 
    	etaInMins = result["route"]["duration"] / 60;
    	calculateArrivalTime(data, etaInMins);
    	//console.log(places);
    	//displayAll();
    } catch (error) {
    	console.error(error);
    }
}

async function calculateArrivalTime(data, etaInMins) {  //converts the duration in minutes into hours
        const currentHour = present.getHours();
        if (currentHour > 12) {
            departHour += 24;
        }
        const minutes = present.getMinutes();   //get present minute
        originHour = departHour - currentHour;
        if (originHour < 0) {
            originHour = originHour * -1;
        }
        hours = 0;
        if (minutes > 29) { //this is for the edgecase for when you query the travel duration of 2 places when it's close to the next hour presently
            hours += 1;
        }
    	while (etaInMins > 60) {
    	    etaInMins -= 60;
    	    hours += 1;
    	}
    	if (etaInMins > 29) {   //if left over minutes is past 29 mins, then round the hour up
    	    hours += 1;
    	}
    	hours += originHour;
    	origin = data.slice(0, 2);
    	dest = data.slice(2);
    	displayAll(origin, dest, originHour, hours);
}

async function displayAll(origin, dest, originHour, hours) {
        document.write(`<h3>*Refresh page to query more destinations</h3>`)
        document.write( from + " weather (From hour of departure):<br>");
    	await getWeather(origin, originHour);
    	document.write("<br><br>" + to + " weather (once destination is reached by car rounded by the hour):<br>");
    	await getWeather(dest, hours);
    	message = "Enter a place within Ireland";
    	to = "";
    	from = "";
}


//- lat: 53.33306N
//- lon: 6.24889W

function home() {   //starting function, user inputs where they're coming from, restricted to Ireland only"
    document.write ( `
    <div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
    <h3> Input a place within Ireland: </h3>
    <INPUT style="width:50vw;" id=query value="Dublin" >
    <INPUT style="width:50vw;" id=time value="Hour of departure in military time (optional, will use current time if left blank)">
    <button onclick="getPlace();"     class=ab-normbutton > Send </button> 
    </div>
    ` );
}

function destination() {    //destination, user inputs where they want to go, again, restricted to Ireland only"
    document.write ( `
    <div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
    <h3> Destination within Ireland: </h3>
    <INPUT style="width:50vw;" id=query value="Somewhere else" >
    <button onclick="getPlace();"     class=ab-normbutton > Send </button> 
    </div>
    ` );
}

home();