import { wwwAPI } from "@/utilities/wwwAPI";
import { getMillis } from "taehui-lib/date";

export default function setTaehuiStore() {
  return {
    avatarCipher: "",
    autoLogIn: false,
    totem: "",
    taehuiAvatarID: "",
    taehuiAvatarName: "",
    taehuiLevel: 0,
    taehuiFax: "",
    taehuiAvatarIntro: "",

    setAvatarCipher(avatarCipher: string) {
      this.avatarCipher = avatarCipher;
    },

    setAutoLogIn(autoLogIn: boolean) {
      this.autoLogIn = autoLogIn;
    },

    setSession({
      totem,
      avatarID,
      avatarName,
      level,
      fax,
      avatarIntro,
    }: {
      totem?: string;
      avatarID?: string;
      avatarName?: string;
      level?: number;
      fax?: string;
      avatarIntro?: string;
    }) {
      if (totem) {
        this.totem = totem;
      }
      if (avatarID) {
        this.taehuiAvatarID = decodeURIComponent(avatarID);
      }
      if (avatarName) {
        this.taehuiAvatarName = decodeURIComponent(avatarName);
      }
      if (level) {
        this.taehuiLevel = level;
      }
      if (fax) {
        this.taehuiFax = decodeURIComponent(fax);
      }
      if (avatarIntro) {
        this.taehuiAvatarIntro = decodeURIComponent(avatarIntro);
      }
    },

    wipeSession() {
      this.totem = "";
      this.taehuiAvatarID = "";
      this.taehuiAvatarName = "";
      this.taehuiLevel = 0;
      this.taehuiFax = "";
      this.taehuiAvatarIntro = "";
    },

    saveTotem() {
      window.sessionStorage.setItem("totem", this.totem);
    },

    async loadTotem() {
      const totem = window.sessionStorage.getItem("totem");
      if (totem) {
        const { status, data } = await wwwAPI.patch("/avatar/totem", null, {
          headers: { millis: getMillis(), totem },
        });
        if (status === 201) {
          this.setSession({ totem, ...data });
        }
      }
    },

    get isSU() {
      return this.taehuiLevel === 2;
    },
  };
}
