const cityForm = document.querySelector("form");
const card = document.querySelector(".card");
const details = document.querySelector(".details");
const time = document.querySelector("img.time")
const icon = document.querySelector(".icon img")
const forecast = new Forecast();
console.log(forecast);

const updateUI = (data) => {

    console.log(data)
    // const cityDets = data.cityDets;
    // const weather = data.weather;

    // das Gleiche als da oben
    // destructure properties
    const { cityDets, weather } = data;

    // Aktualisierung der Stadt-Daten (Template)
    details.innerHTML = `
        <h5 class="my-3">${cityDets.EnglishName}</h5>
        <div class="my-3">${weather.WeatherText}</div>
        <div class="display-4 my-4">
            <span>${weather.Temperature.Metric.Value}</span>
                <span>&deg;</span>
        </div>
    `;

    // aktualisierung des day/night Fotos
    const iconSrc = `img/icons/${weather.WeatherIcon}.svg`;
    icon.setAttribute("src", iconSrc);

    let timeSrc = null;
    weather.IsDayTime ? timeSrc = "img/day.svg" : timeSrc = "img/night.svg";

    time.setAttribute("src", timeSrc);

    if (card.classList.contains("d-none")) {
        card.classList.remove("d-none")
    }
};

const updateCity = async (city) => {

    // console.log(city);
    const cityDets = await getCity(city);
    const weather = await getWeather(cityDets.Key);

    return {
        cityDets: cityDets,
        weather: weather
        // cityDets,
        // weather
    };
}

cityForm.addEventListener("submit", e => {
    // prevent default action
    e.preventDefault();

    // fordern den Stadt-Wert
    const city = cityForm.city.value.trim();
    cityForm.reset();

    // update the UI with new city
    forecast.updateCity(city)
        .then((data) => updateUI(data))
        .catch(err => console.log(err));

    // Einstellung den localen Speicher
    localStorage.setItem("city", city);
});

// wenn eine Stadt schon im lokalen Speciher existiert, dann wird diese Stadt bei dem nächsten Besuch der App verwendet
if (localStorage.getItem("city")) {
    forecast.updateCity(localStorage.getItem("city"))
        .then(data => updateUI(data))
        .catch(err => console.log(err))
}
