import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  state: () => {
    const defaultAvatar = "data:image/jpeg;base64,[encoded data, 16376 characters]";
    if (!localStorage.getItem("profile")) {
      return {
        profileID: "",
        userName: "",
        email: "",
        avatar: defaultAvatar,
        memberSince: "",
        pfp: "",
        is2FAEnabled: false,
      }
    }
    const dataProfile = JSON.parse(localStorage.getItem("profile")!);
    const dataUser = JSON.parse(localStorage.getItem("user")!);
    const dataAttachments = JSON.parse(localStorage.getItem("attachments")!);
    const dateCreate = new Date(Date.parse(dataProfile.created_at));
    const yyyy = dateCreate.getFullYear().toString();
    const mm = dateCreate.getMonth() + 1;
    const dd = dateCreate.getDate();
    let stringDD = dd.toString();
    let strinMM = mm.toString();
    if (dd < 10) {
      stringDD = '0' + stringDD
    };
    if (mm < 10) {
      strinMM = '0' + strinMM;
    }
    let avatar = defaultAvatar;
    if (dataAttachments.avatar != null) {
      avatar = dataAttachments.avatar.url;
    }
    const formattedToday = stringDD + '/' + strinMM + '/' + yyyy;
    return {
      avatar: avatar,
      profileID: dataProfile.id || "",
      userName: dataProfile.first_name || "",
      userSurname: dataProfile.surname || "",
      email: dataUser.email || "",
      memberSince: formattedToday,
      pfp: "https://picsum.photos/id/22/200/300",
      is2FAEnabled: false,
    };
  },

  actions: {
    toggle2FA() {
      this.is2FAEnabled = !this.is2FAEnabled;
    },

    changeUserName(userFirst: string, userSurname: string) {
      this.userName = userFirst;
      this.userSurname = userSurname;
    },
    changeAvatar(avatar: string) {
      this.avatar = avatar;
    },
  },
});
