
<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 { inject } from 'vue'
import { VaFileUpload } from "vuestic-ui";
import axios from "axios";
import { useToast } from "vuestic-ui/web-components";

const HOST = inject('HOST');
const { init } = useToast();

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);
    axios.post(`${HOST}/api/v0/attachment/upload`, formData, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem("token")}`,
        }
    }).then(function (response) {
        axios
            .post(`${HOST}/api/v0/workouts`, {
              "attachment_id": response.data.id,
              "name": "Новая тренировка",
            }, {
                  headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }
              })
            .then((response) => {
              init({ message: "Тренировка успешно загружена!", color: "success" });
            })
            .catch((error) => {
                init({
                  message: "Что-то пошло не так.",
                  color: "error",
                });

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

</script>

  
