2** EPITECH PROJECT, 2024
10// Import the list of cities for the weather api
11import CityList from "../ressources/city.list.min.json"
12// import CityList from "../ressources/city.list.tiny.json"
15export namespace WeatherApi {
18 export function get_location_coordinates() {
19 console.log("get_location_coordinates");
21 // console.log(`CityList: ${JSON.stringify(CityList)}: CityList`);
23 let coordinate_equivalence: Record<string, { lat: number; lon: number }> = Object();
24 for (let i = 0; i < CityList.length; i++) {
25 let city = CityList[i];
28 keyName += `${city.name}, `;
31 keyName += `${city.state}, `;
33 keyName += city.country;
34 coordinate_equivalence[String(keyName)] = { "lat": city.coord.lat, "lon": city.coord.lon };
36 // console.log(`Coordinate Equivalence: ${JSON.stringify(coordinate_equivalence)} : coodinate equivalence`);
37 return coordinate_equivalence;
40 export const coordinate_equivalence = get_location_coordinates();
41 export const available_cities = Object.keys(coordinate_equivalence);
43 export interface Coordinates {
51 export async function getCountryCoordinates(country: string, database: DB, user_info: any, widget_index: Number): Promise<Coordinates | null> {
52 console.log("getCountryCoordinates");
53 let city = available_cities[Math.floor(Math.random() * available_cities.length - 1)];
55 if (coordinate_equivalence.hasOwnProperty(country)) {
56 coords = coordinate_equivalence[country];
59 database.updateTable("user_widgets", ["widget_option"], [city], `widget_index='${widget_index}' AND user_id='${user_info.id}'`, []);
60 coords = coordinate_equivalence[city];
63 return { coords: { latitude: String(coords.lat), longitude: String(coords.lon) }, city: city };
65 console.error("Error fetching coordinates: No results found for: ", country);
70 export async function getWeather(id: string, country: string, weatherKey: string, database: DB, user_info: any, widget_index: Number): Promise<{ html: String, location: String }> {
71 console.log("getWeather");
72 const coords = await getCountryCoordinates(country, database, user_info, widget_index);
76 const { latitude, longitude } = coords.coords;
77 location = coords.city;
78 const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&mode=html&appid=${weatherKey}&units=metric&lang=en`;
80 // Create and inject the iframe dynamically
84 html = `<iframe src="${weatherUrl}" width="${width}" height="${height}" frameborder="0" scrolling="no" id="${id}" data-country="${country}"></iframe>`;
86 const msg = "Could not retrieve weather data.";
88 html = `<p id="${id}">${msg}</p>`;
90 return { html: html, location: location };
93 export async function get_weather_locations(dropdown_id: string, command: string, location: String) {
94 console.log("get_weather_locations");
95 let html = `<select id="${dropdown_id}" name="${dropdown_id}" onchange="${command}">`;
96 for (let i = 0; i < available_cities.length; i++) {
97 if (available_cities[i] === location) {
98 html += `<option value="${available_cities[i]}" selected>${available_cities[i]}</option>`;
100 html += `<option value="${available_cities[i]}">${available_cities[i]}</option>`;
107 export async function get_weather_widget(widget_name: string, index: number, user_info: any, database: DB) {
108 console.log("get_weather_widget");
110 const widget_id = `${widget_name}_${index}`;
111 const country = await database.getContentFromTable("user_widgets", ["widget_option"], `widget_index='${index}' AND user_id='${user_info.id}'`);
112 const apiKey = await database.getContentFromTable("widgets", ["api_key"], "widget_name='weather'");
113 if (!apiKey || apiKey.length == 0) {
114 return "<p>Widget gathering error, the content for the given widget could not be fetched successfully.</p>";
116 const weatherKey = apiKey[0].api_key || null;
117 // console.log("widget_id", widget_id);
118 // console.log("Country", country);
119 // console.log("Weather key", weatherKey);
120 let countryCleaned = country[0].widget_option;
121 if (countryCleaned === undefined || countryCleaned.length === 0 || !countryCleaned || countryCleaned === null) {
124 // console.log("Country cleaned", countryCleaned);
125 const weatherBody = await getWeather(`${widget_id}-iframe`, countryCleaned, weatherKey, database, user_info, index);
126 const weatherDropdown = await get_weather_locations(`${widget_id}-dropdown`, `getWeather('${widget_id}-iframe', this.value, this)`, weatherBody.location);
127 // console.log("Weather body", weatherBody);
128 // console.log("Weather dropdown", weatherDropdown);
129 content += `<div id="${widget_id}" data-country="${weatherBody.location}" data-id="${index}">`;
130 content += weatherDropdown;
131 content += weatherBody.html;
133 // console.log("Widget content:", content);