<template>
    <div>
        <h2>Météo</h2>
        <p v-if="loading"></p>
        <div v-else>
            <div>{{ meteo.city.name }}</div>
            <div>
                <div>{{ meteo.list[0].dt_txt }}</div>
                <div>Temp : {{ meteo.list[0].main.temp }} °C</div>
                <div>Hum : {{ meteo.list[0].main.humidity }} %</div>
                <div>Pres : {{ meteo.list[0].main.pressure }} hPa</div>
                <div>{{ meteo.list[0].weather[0].description }}</div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "OpenWeatherCard",
        data: function () {
            return {
                loading: true,
                meteo: null,
            }
        },
        mounted() {
            let refreshMeteo = false

            if(localStorage.getItem('meteo')) {
                this.meteo = JSON.parse(localStorage.getItem('meteo'))
                let deltaTime = new Date() - new Date(this.meteo.list[0].dt_txt)
                if (deltaTime/1000/3600 > 3) {
                    refreshMeteo = true
                }
                this.loading = false
                console.log('in storage', this.meteo, this.meteo.city.name)
            } else {
                refreshMeteo = true
            }

            if (refreshMeteo) {
                console.log("refreshing meteo data")
                axios.get('/api/meteo')
                    .then(response => {
                        this.meteo = response.data
                        this.loading = false
                        localStorage.setItem('meteo', JSON.stringify(response.data));
                    })
                    .catch(error => {
                        alert('Unable to fetch meteo.')
                    })
            }
        },
    }
</script>

