
<template>
  <h1 class="page-title">Тренировки</h1>

  <section class="news-feed">
  <template v-if="workoutItems.length==0">
    <div>Тренировки не найдены</div>
  </template>
  <template v-if="workoutItems.length>0" v-for="(item, index) in workoutItems" :key="item.id">
    <article class="news-item">
      <div class="news-item-header" v-on:click="openWorkout(item.id)">
        <h3>{{ item.name }}</h3>
        <VaIcon name="delete_forever" size="22px" color="#bbc1c3" class="news-item-icon" @click="(event: any) => deleteItem(item.id, event)"/>
      </div>
        <ul class="metadata">
            <li v-if="item.workouted_at"><span>Дата:</span> {{ formatTime(item.workouted_at) }}</li>
            <li v-if="item.speed"><span>Скорость:</span> {{ speedConvert(item.speed) }} км/ч</li>
            <li v-if="item.heart_rate"><span>Пульс:</span> {{ item.heart_rate }} уд  /мин</li>
            <li v-if="item.distantion"><span>Расстояние:</span> {{ distConvert(item.distantion) }} км</li>
            <li v-if="item.duraion_sec"><span>Продолжительность:</span> {{ secondsToDuration(item.duraion_sec) }} </li>
            <li v-if="item.cadence"><span>Каденс:</span> {{ item.cadence }} об/мин</li>
            <li v-if="item.power"><span>Мощность:</span> {{ Math.round(item.power) }} Вт</li>
            <li v-if="item.external_links && item.external_links.values.length > 0"><span>Ссылки:</span> <a :href="item.external_links?.values[0].value" target="_blank">Дзен</a></li>
        </ul>
        <div v-if="item.attachment" 
        class="image-container" 
        :style="{'background-image': `url(${item.attachment.url})` }"
        v-on:click="openWorkout(item.id)"></div>
    </article>
  </template>
  </section>
</template>
<script setup lang="ts">

import { AxiosResponse, AxiosInstance } from "axios";
import { ref, inject } from 'vue';
import { useToast } from "vuestic-ui/web-components";
import { useRouter } from "vue-router";
import { WorkoutItem, formatTime, secondsToDuration, distConvert, speedConvert } from "./Definitions.vue";


const { push } = useRouter();
const axiosAuth= inject('axiosAuth') as AxiosInstance;
let workoutItems = ref<Array<WorkoutItem>>([]);
const { init } = useToast();

const deleteItem = (id: string, event: any) => {
  event.stopPropagation();
  axiosAuth
  .delete(`/api/v0/workouts/${id}`)
  .then((_: AxiosResponse) => {
      init({
        message: "Тренировка успешно удалена.",
        color: "success",
      });
      initWorkouts();
  })
  .catch((error: any) => {
    console.log(error);
      init({
        message: "Что-то пошло не так.",
        color: "error",
      });
  });
};



const openWorkout = (id: string) => {
  push({ name: "workout_item", params: {id: id}}).catch((error) => {});
};

const initWorkouts = () => {
  axiosAuth
    .get(`/api/v0/workouts`)
    .then((response: AxiosResponse) => {
      workoutItems.value = response.data.results;
    })
    .catch((error: any) => {
      console.log(error);
        init({
          message: "Что-то пошло не так.",
          color: "error",
        });
    });
};

initWorkouts();
</script>

<style>
.image-container {
  cursor: pointer;
  height: 300px;
  width: 100%;
  background-position: 50% 50%;
  background-repeat: no-repeat;
  background-size: cover;
}

.news-feed {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 7rem;
}

.news-item {
    display: flex;
    flex-direction: column;
    padding: 1rem;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
    transition: transform 0.2s ease-in-out;
    width: 100%;
}

.news-item-header {
  cursor: pointer;
  display: flex;
  justify-content: space-between;

}
.news-item-icon {
  cursor: pointer;
}


.news-item h3 {
    font-weight: bold;
    color: #3d3d3d;
}

.metadata {
  border-top: #9c9a9a 1px solid;
}

.metadata li {
    list-style: none;
    display: inline-block;
    margin-left: 1rem;
}

.metadata span {
    font-size: 0.9em;
    opacity: 0.7;
}

</style>
