<script setup>
import { mapStores } from 'pinia'
import { useWeatherStore } from '../stores/weather'
</script>

<script>
export default {

    data() {
        return {
            coordinates: null,
            hourly: null,
            chunks: [],
        }
    },

    computed: {
        ...mapStores(useWeatherStore),
    },

    activated() {
        if (this.coordinates != this.weatherStore.coordinates) {
            this.hourly = null
            this.chunks = []
            this.fetchHourly()
        }
    },

    methods: {

        async fetchHourly() {

            const weather = await this.weatherStore.getWeather()
            this.coordinates = this.weatherStore.coordinates

            const url = weather.properties.forecastHourly
            const response = await fetch(url)
            this.hourly = await response.json()

            this.chunks = []
            let chunk = null
            for (let period of this.hourly.properties.periods.slice(0, 12)) {
                const date = new Date(period.startTime).toLocaleDateString('en-US', {
                    dateStyle: 'full',
                })
                if (!chunk || chunk.date != date) {
                    chunk = {
                        date,
                        periods: [],
                    }
                    this.chunks.push(chunk)
                }
                chunk.periods.push(period)
            }
        },

        renderTime(period) {
            const date = new Date(period.startTime)
            return date.toLocaleTimeString('en-US', {timeStyle: 'short'})
        },
    },
}
</script>

<template>
  <main>

    <o-button variant="primary"
              size="small"
              icon-left="arrow-left"
              @click="$router.push('/weather')">
      Back
    </o-button>

    <h5 class="is-size-5">{{ weatherStore.cityState }}</h5>
    <br />

    <div v-for="chunk in chunks"
         :key="chunk.date">

      <p class="block has-text-weight-bold">{{ chunk.date }}</p>

      <div v-for="period in chunk.periods"
           :key="period.number"
           class="hourly-period is-size-7 has-text-weight-bold">

        <div>
          <p>{{ renderTime(period) }}</p>
          <img :src="period.icon" />
        </div>

        <div>
          <p>{{ period.shortForecast }}</p>
          <p>Temp: {{ period.temperature }} &deg; {{ period.temperatureUnit }}</p>
          <p>Wind: {{ period.windDirection }} @ {{ period.windSpeed }}</p>
        </div>
      </div>

      <br />
    </div>

  </main>
</template>

<style>

.hourly-period {
    background: #eee;
    border: 1px solid #b3b3b3;
    border-collapse: collapse;
    padding: 0.5rem 1rem;
    display: flex;
    gap: 1rem;
    align-items: center;
}

</style>
