
<template>
  <h1 class="page-title">Загрузить тренировку</h1>
  <VaFileUpload 
  v-model="file" 
    file-types="gpx,fit" 
    type="single" 
    v-on:update:model-value="onFileChanged"
    color="#F4F6F8"
  />
</template>
<script setup lang="ts">
import { AxiosResponse, AxiosInstance } from "axios";
import { inject } from 'vue'
import { VaFileUpload } from "vuestic-ui";
import { useToast } from "vuestic-ui/web-components";
import { useRouter } from "vue-router";

const axiosAuth= inject('axiosAuth') as AxiosInstance;
const { init } = useToast();
const router = useRouter();

let file: { 
  name: "Example", 
  url: "",
  size: 0, 
  webkitRelativePath: "", 
  type: "", 
  arrayBuffer: () => Promise<ArrayBuffer> ,
  slice: (start?: number | undefined, end?: number | undefined, contentType?: string | undefined) => Blob, 
  stream: () => ReadableStream<Uint8Array>, 
  text: () => Promise<string>,
};

function onFileChanged() {
    var formData = new FormData();
    formData.append("file", file);
    axiosAuth.post(`/api/v0/attachment/upload`, formData).then(
      function (response: AxiosResponse) {
        axiosAuth
            .post(`/api/v0/workouts`, {
              "attachment_id": response.data.id,
              "name": "Новая тренировка",
            })
            .then((response: AxiosResponse) => {

              init({ message: "Тренировка успешно загружена!", color: "success" });
              router.push({ name: "workout_item", params: { id: response.data.id }  });
            })
            .catch((error: any) => {
                init({
                  message: "Что-то пошло не так.",
                  color: "error",
                });

            });
        })
        .catch(function (error: any) {
          init({
            message: "Что-то пошло не так.",
            color: "error",
          });
        });
}

</script>

  
