File size: 6,487 Bytes
387210e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320a5a6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
document.getElementById('search-button').addEventListener('click', function() {
    let city = document.getElementById('city-input').value;
    fetchWeatherData(city);
    addToCityHistory(city);
});
document.getElementById('clear-history-button').addEventListener('click', function() {
    clearCityHistory();
});
let cityHistory = [];


function clearCityHistory() {
    cityHistory = [];
    displayCityHistory();
    toggleClearHistoryButton();
}

function toggleClearHistoryButton() {
    let clearHistoryButton = document.getElementById('clear-history-button');
    if (cityHistory.length > 0) {
        clearHistoryButton.style.display = 'block';
    } else {
        clearHistoryButton.style.display = 'none';
    }
}

function addToCityHistory(city) {
    if (!cityHistory.includes(city)) {
        cityHistory.push(city);
    }
    displayCityHistory();
    toggleClearHistoryButton();
}

function displayCityHistory() {
    let historyContainer = document.getElementById('city-history');
    historyContainer.innerHTML = '<strong>City History:</strong> ';
    
    cityHistory.forEach((city, index) => {
        let link = document.createElement('span');
        link.classList.add('city-history-item');
        link.textContent = city;
        link.addEventListener('click', function() {
            // console.log('City clicked:', city);
            fetchWeatherData(city);
        });
        
        if (index < cityHistory.length - 1) {
            historyContainer.appendChild(link);
            historyContainer.innerHTML += ', ';
        } else {
            historyContainer.appendChild(link);
        }
    });
}


document.getElementById('location-button').addEventListener('click', function() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            let lat = position.coords.latitude;
            let lon = position.coords.longitude;
            fetchWeatherDataByLocation(lat, lon);
            addToCityHistory("Current Location");
        });
    } else {
        alert('Geolocation is not supported by this browser.');
    }
});

function fetchWeatherData(city) {
    fetch(`/weather?city=${city}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert(data.error);
            } else {
                displayWeatherData(data);
            }
        })
        .catch(error => console.error('Error:', error));
}

function fetchWeatherDataByLocation(lat, lon) {
    fetch(`/weatherlocation?lat=${lat}&lon=${lon}`)
        .then(response => response.json())
        .then(data => {
            if (data.error) {
                alert(data.error);
            } else {
                displayWeatherData(data);
            }
        })
        .catch(error => console.error('Error:', error));
}

function loadMoreForecast() {
    fetch(`/load_more_forecast`)
        .then(response => response.json())
        .then(data => {
	    if (data.error) {
                alert(data.error);
            } else {
                renderForecast(data, true); // Append new forecast data
            } 
    
        })
        .catch(error => console.error('Error loading more forecast:', error));
}

function displayWeatherData(data) {
    let currentWeather = document.getElementById('current-weather');
    currentWeather.innerHTML = `
        <div class="weather-details">
            <h2>${data.location.name} (${data.current.last_updated})</h2>
            <p>Temperature: ${data.current.temp_c}°C</p>
            <p>Wind: ${data.current.wind_kph} KPH</p>
            <p>Humidity: ${data.current.humidity}%</p>
        </div>
        <div class="weather-icon">
            <img src="${data.current.condition.icon}" alt="${data.current.condition.text}">
            <p>${data.current.condition.text}</p>
        </div>
    `;
    
    let forecast = document.getElementById('forecast');
    forecast.innerHTML = '';
    
    let lastFourDays = data.forecast.forecastday.slice(1, 5);
    lastFourDays.forEach(day => {
        forecast.innerHTML += `
            <div class="forecast-day">
                <h3>${day.date}</h3>
                <img src="${day.day.condition.icon}" alt="${day.day.condition.text}">
                <p>Temp: ${day.day.avgtemp_c}°C</p>
                <p>Wind: ${day.day.maxwind_kph} KPH</p>
                <p>Humidity: ${day.day.avghumidity}%</p>
            </div>
        `;
    });

    if (forecast.innerHTML != '') {
        document.getElementById('load-more-btn').style.display = 'block';
    }
}


function renderForecast(data, append = false) {
    const forecastContainer = document.getElementById('forecast');
    if (!append) {
        forecastContainer.innerHTML = '';
    }
    let forecast  = data.forecast.forecastday.slice(-4);

    let rows = Math.ceil(forecast.length / 4);
    for (let i = 0; i < rows; i++) {
        const row = document.createElement('div');
        row.className = 'forecast-row';
        row.style.display = 'flex';
        row.style.justifyContent = 'space-between';
        for (let j = 0; j < 4; j++) {
            let dayIndex = i * 4 + j;
            if (dayIndex < forecast.length) {
                const day = forecast[dayIndex];
                const forecastElement = document.createElement('div');
                forecastElement.className = 'forecast-day';
                forecastElement.innerHTML = `
                    <h3>${day.date}</h3>
                    <img src="${day.day.condition.icon}" alt="${day.day.condition.text}">
                    <p>Temp: ${day.day.avgtemp_c}°C</p>
                    <p>Wind: ${day.day.maxwind_kph} KPH</p>
                    <p>Humidity: ${day.day.avghumidity}%</p>
                `;
                row.appendChild(forecastElement);
            }
        }
        forecastContainer.appendChild(row);
    }
}


document.getElementById('subscribe-form').addEventListener('submit', function(event) {
    event.preventDefault();
    let email = document.getElementById('email-input').value;
    fetch('/subscribe', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
               },
        body: JSON.stringify({ email: email })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
        } else {
            alert(data.message);
        }
    })
    .catch(error => console.error('Error:', error));
});