import React from "react";
import { User } from "user/domain/userEntity";
import { updateEmailUseCase } from "user/useCases/updateEmailUseCase";
import { updatePersonalInfoUseCase } from "user/useCases/updatePersonalInformationUseCase";
import { UserStore } from "../domain/userStore";
import { changeUsernameUseCase } from "../useCases/changeUsernameUseCase";
import { getUserUseCase } from "../useCases/getUserUseCase";
import { toggleUserTwoFactorUseCase } from "../useCases/toggleUserTwoFactorUseCase";

function useUserViewModel(store: UserStore) {
  const getUser = React.useCallback(
    function () {
      getUserUseCase({
        loadUser: store.loadUser,
      });
    },
    [store.loadUser]
  );

  const toggleTwoFactorAuthenitcation = React.useCallback(
    function () {
      toggleUserTwoFactorUseCase({
        user: store.user,
        setUser: store.setUser,
        updateUser: store.updateUser,
      });
    },
    [store.user, store.updateUser, store.setUser]
  );

  const changeUsername = React.useCallback(
    (username: string) =>
      changeUsernameUseCase(
        {
          user: store.user,
          setUser: store.setUser,
          updateUser: store.updateUser,
        },
        username
      ),
    [store.user, store.setUser, store.updateUser]
  );

  const updateEmail = React.useCallback(
    (payload: string) =>
      updateEmailUseCase(
        {
          user: store.user,
          setUser: store.setUser,
          updateUser: store.updateUser,
        },
        payload
      ),
    [store.user, store.setUser, store.updateUser]
  );

  const updatePersonalInfo = React.useCallback(
    (payload: Pick<User, "username" | "firstname" | "lastname">) =>
      updatePersonalInfoUseCase(
        {
          user: store.user,
          setUser: store.setUser,
          updateUser: store.updateUser,
        },
        payload
      ),
    [store.user, store.setUser, store.updateUser]
  );

  return {
    user: store.user,
    twoFactorEnabled: store.user?.twoFactorEnabled,
    isLoading: typeof store.user === "undefined" || store.isLoading,
    getUser,
    toggleTwoFactorAuthenitcation,
    changeUsername,
    updateEmail,
    updatePersonalInfo,
  };
}

export { useUserViewModel };
