<template>
  <VaAvatar size="large" color="warning">
    <img
        :src="store.avatar"
        width="100"
        height="100"
        alt=""
      >
  </VaAvatar>
  <VaFileUpload 
  v-model="file" 
    file-types="image/*" 
    type="single" 
    v-on:update:model-value="onFileChanged"
    color="#F4F6F8"
  />
  <div class="flex flex-col justify-center">
    <h2 class="text-[28px] md:text-[32px] leading-10 font-bold">
      {{ store.userName }}
    </h2>
    <div class="flex space-x-1 text-[13px] leading-4">
      <p>Зарегистрирован с</p>
      <p>{{ store.memberSince }}</p>
    </div>
  </div>
</template>
<script lang="ts" setup> 
import { AxiosResponse, AxiosInstance } from "axios";
import { inject } from 'vue'
import { VaFileUpload } from "vuestic-ui";
import { useUserStore } from "../../../stores/user-store";
import { useToast } from "vuestic-ui/web-components";
import { ref } from 'vue';

const axiosAuth = inject('axiosAuth') as AxiosInstance;
const store = useUserStore();
const { init } = useToast();
const avatar = ref(store.avatar);

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) {
        let dataUser = JSON.parse(localStorage.getItem("user")!);
        dataUser["attachment_id"] = response.data.id;
        store.changeAvatar(response.data.url);
        avatar.value = response.data.url;
        axiosAuth
            .patch(`/api/v0/profiles/${store.profileID}`, {
              "user": dataUser,
            })
            .then((response: any) => {
              init({ message: "Фото успешно загружено!", color: "success" });
            })
            .catch((error: any) => {
                init({
                  message: "Что-то пошло не так.",
                  color: "error",
                });

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

function readFile(event: ProgressEvent<FileReader>) {
  if (event == null) {
    return;
  }
  if (event.target == null) {
    return;
  }
  console.log(event.target.result);
}

</script>

<style>
.custom-upload-file-area {
  width: max-content;
  padding: 1rem;
  border: 1px solid #cccccc;
  text-align: center;
}
</style>