import { TFunction } from "i18next";
import { toast } from "react-toastify";
import { sprintf } from "sprintf-js";
import { getMillis } from "taehui-ts/date";

import { wwwAXIOS } from "src/Www";

export default function setAvatarStore() {
  return {
    totem: "",
    taehuiAvatarID: "",
    taehuiAvatarName: "",
    taehuiLevel: 0,
    taehuiFax: "",
    taehuiAvatarIntro: "",

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

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

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

    async notSignIn(t: TFunction) {
      const { status } = await wwwAXIOS.delete("/avatar/totem", {
        headers: {
          millis: getMillis(),
          totem: this.totem,
        },
      });
      if (status === 204) {
        toast.success(sprintf(t("notSignedInText"), this.taehuiAvatarName));
        this.setSession({
          totem: "",
          avatarID: "",
          avatarName: "'",
          level: 0,
          fax: "",
          avatarIntro: "",
        });
        this.saveTotem();
        return true;
      } else {
        return false;
      }
    },

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