<template>
  <Loading :loading="loading" :message="error" type="danger">
    <div class="block">
      <router-link class="button" to="/new">
        <Icon name="plus">New container</Icon>
      </router-link>
    </div>
    <div v-if="containers.length" class="box">
      <ul>
        <li v-for="container in containers" :key="container.id">
          <router-link :to="`/show/${container.name}`">
            <Icon
              :class="`has-text-${status_icon(container).type} m-2`"
              :name="status_icon(container).name"
              >{{ container.name }}</Icon
            >
          </router-link>
        </li>
      </ul>
    </div>
  </Loading>
</template>

<script lang="ts">
import axios, { AxiosError } from 'axios'
import type { Container } from '../types'
import Icon from '../components/Icon.vue'
import Loading from '../components/Loading.vue'

export default {
  name: 'Home',
  components: {
    Icon,
    Loading,
  },
  data() {
    return {
      containers: [] as Container[],
      error: '',
      loading: true,
    }
  },
  async mounted() {
    try {
      const response = await axios.get<Container[]>('/api/containers')
      this.containers = response.data
    } catch (error) {
      console.error(error)
      this.error =
        error instanceof AxiosError ? error.message : 'Error loading containers'
    } finally {
      this.loading = false
    }
  },
  methods: {
    status_icon(container: Container): { name: string; type: string } {
      switch (container.status) {
        case 'running':
          return { name: 'play', type: 'success' }
        case 'restarting':
          return { name: 'refresh', type: 'danger' }
        case 'paused':
          return { name: 'pause', type: 'warning' }
        case 'exited':
          return { name: 'stop', type: 'danger' }
        default:
          return { name: 'question-circle', type: 'warning' }
      }
    },
  },
}
</script>
