import { RootState } from "app/store";
import { ROLE } from "./constants";

export const selectInputValidationErrors = (state: RootState) => {
  const { name, email, role, authorId } = state.user.apps.addUser;

  // 必須項目のチェック
  const hasErrorEmptyName = name === "";
  const hasErrorEmptyEmail = email === "";
  const hasErrorEmptyAuthorId = role === ROLE.AUTHOR && authorId === "";

  const hasErrorIncorrectAuthorId = checkErrorIncorrectAuthorId(
    authorId ?? undefined,
    role
  );

  const hasErrorIncorrectEmail = email.match(/^[^@]+@[^@]+$/)?.length !== 1;

  return {
    hasErrorEmptyName,
    hasErrorEmptyEmail,
    hasErrorEmptyAuthorId,
    hasErrorIncorrectEmail,
    hasErrorIncorrectAuthorId,
  };
};
export const checkErrorIncorrectAuthorId = (
  authorId: string | undefined,
  role: string
): boolean => {
  if (!authorId || role !== ROLE.AUTHOR) {
    return false;
  }

  // 半角英数字と_の組み合わせで１６文字まで
  const charaTypePattern = /^[A-Z0-9_]{1,16}$/;
  const charaType = new RegExp(charaTypePattern).test(authorId);

  return !charaType;
};

export const selectName = (state: RootState) => state.user.apps.addUser.name;
export const selectEmail = (state: RootState) => state.user.apps.addUser.email;
export const selectRole = (state: RootState) => state.user.apps.addUser.role;
export const selectAuthorId = (state: RootState) =>
  state.user.apps.addUser.authorId;
export const selectTypistGroupId = (state: RootState) =>
  state.user.apps.addUser.typistGroupId;
export const selectAutoRenew = (state: RootState) =>
  state.user.apps.addUser.autoRenew;
export const selectLicenseAlert = (state: RootState) =>
  state.user.apps.addUser.licenseAlert;
export const selectNtotification = (state: RootState) =>
  state.user.apps.addUser.notification;
export const selectDomain = (state: RootState) => state.user.domain;
export const selectIsLoading = (state: RootState) => state.user.apps.isLoading;
