<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 { inject } from 'vue'
import { VaFileUpload } from "vuestic-ui";
import { useUserStore } from "../../../stores/user-store";
import axios from "axios";
import { useToast } from "vuestic-ui/web-components";
import { ref } from 'vue'
const store = useUserStore();
const HOST = inject('HOST');
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);
    axios.post(`${HOST}/api/v0/attachment/upload`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${localStorage.getItem("token")}`,
        }
    }).then(function (response) {
        console.log('SUCCESS!!', response.data);
        let dataUser = JSON.parse(localStorage.getItem("user")!);
        dataUser["attachment_id"] = response.data.id;
        store.changeAvatar(response.data.url);
        avatar.value = response.data.url;
        axios
            .patch(`${HOST}/api/v0/profiles/${store.profileID}`, {
              "user": dataUser,
            }, {
                  headers: { Authorization: `Bearer ${localStorage.getItem("token")}` }
              })
            .then((response) => {
              init({ message: "Фото успешно загружено!", color: "success" });
            })
            .catch((error) => {
              console.log("1", error);
                init({
                  message: "Что-то пошло не так.",
                  color: "error",
                });

            });
        })
        .catch(function (error) {
          console.log("2", error);
          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>