import { mapState, mapActions } from "pinia";
import { useAuthStore } from "~/stores/authStore";

export default {
  data() {
    return {
      // mobile: "",
      // username: "",
      // password: "",
      // email: "",
      // repassword: "",
      loading: false,
      submitStatus: null,
      enableResendCode: false,
    };
  },
  computed: {
    ...mapState(useAuthStore, ["isGuest"]),
  },

  methods: {
    ...mapActions(useAuthStore, [
      "login",
      "logout",
      "forget",
      "register",
      "getCaptcha",
      "phoneLogin",
      "loginAsGuest",
      "resetPassword",
      "loginWithGoogle",
      "getActivationCode",
    ]),
    // callFrom : page | modal
    async authBase(methodName, callFrom = "page") {
      const toast = useToast();

      // this.$v.$touch();
      const route = useRoute();
      const router = useRouter();

      const isFormCorrect = await this.v$.$validate();
      if (!isFormCorrect) {
        // Notify user that the form is invalid
        this.submitStatus = "ERROR";
        return;
      } else {
        // do your submit logic here
        this.submitStatus = "PENDING";

        if (this.loading) return false;
        this.loading = true;

        this[methodName]()
          .then((res) => {
            toast.add({
              title: res.message,
              icon: "success",
              timer: 2000,
            });

            if (callFrom == "modal") {
              // fired event cached in the Group.vue and ChatList.vue
              const { $eventBus } = useNuxtApp();
              $eventBus.emit(
                "authenticated-by-modal",
                route.query["invite-id"]
              );
            }
            // if redirected from chat system to relogin.
            else {
              if (route.query.redirectBack) {
                navigateTo({
                  path: route.query.path,
                });
                // router.push({ path: route.query.path });
              }
              // normal mode.
              else {
                navigateTo({
                  path: "/",
                });

                // router.push({ path: "/" });
              }
            }
          })
          .catch((err) => {
            toast.add({
              title: err.message,
              icon: "error",
              timer: 2000,
            });
           
            this.resetCaptcha();
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    doregister() {
      return this.register({
        name: this.name,
        last_name: this.last_name,
        username: this.username,
        password: this.password,
        email: this.email,
        mobile: this.mobile,
        captcha: this.captcha,
      });
    },
    dologin() {
      return this.login({
        username: this.username,
        password: this.password,
        captcha: this.captcha,
      });
    },
    loginGuest() {
      if (this.loading) return false;
      this.loading = true;

      this.loginAsGuest()
        .then((res) => {
          // mySwalToast({
          //   title: "خوش آمدید.",
          //   icon: "success",
          //   timer: 1000,
          // });
          const router = useRouter();

          router.push({
            name: "dashboard",
          });
        })
        .catch((err) => {
          mySwalToast({
            title: err.message,
            icon: "error",
          });
        })
        .finally(() => {
          this.loading = false;
        });

      // return this.loginAsGuest();
    },
    loginWithGoogle() {
      if (this.loading) return false;

      this.loading = true;
      var vm = this;
      this.$gAuth
        .signIn()
        .then((GoogleUser) => {
          var id_token = "";
          for (var key in GoogleUser)
            for (var k in GoogleUser[key])
              if (k == "id_token") id_token = GoogleUser[key][k];
          vm.doLoginGoogle(id_token);
        })
        .catch((error) => {
          mySwalToast({
            title: "خطا",
            text: error,
            icon: "error",
            position: "bottom-end",
            showConfirmButton: false,
            toast: true,
            timer: 1500,
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    doLoginGoogle(token) {
      this.loginWithGoogle({
        token: token,
      })
        .then(() => {
          const router = useRouter();
          router.push({
            name: "systems",
          });
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    goBack() {
      const router = useRouter();
      router.go(-1);
    },
    resetCaptcha() {
      this.getCaptcha().then((res) => {
        this.captchaImage = `data:image/jpeg; charset=utf-8; base64, ${res}`;
      });
    },
  },
};