import { RootState } from "app/store";

export const selectInputValidationErrors = (state: RootState) => {
  // 必須項目のチェック
  const hasErrorEmptyEmail = state.signup.apps.email === "";
  const hasErrorEmptyPassword = state.signup.apps.password === "";
  const hasErrorEmptyCompany = state.signup.apps.company === "";
  const hasErrorEmptyCountry = state.signup.apps.country === "";
  const hasErrorEmptyAdminName = state.signup.apps.adminName === "";
  /* TODO ディーラーはPBI1125対象外
	const hasErrorEmptyDealer = state.signup.apps.dealer === "";
	*/

  const hasErrorIncorrectPassword = !isValidPasswordFormat(
    state.signup.apps.password
  );

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

  return {
    hasErrorEmptyEmail,
    hasErrorEmptyCountry,
    hasErrorEmptyPassword,
    hasErrorEmptyCompany,
    hasErrorEmptyAdminName,
    hasErrorIncorrectEmail,
    hasErrorIncorrectPassword,
  };
};

// 渡された文字列がパスワードポリシーに一致しているかを判定する
const isValidPasswordFormat = (password: string): boolean => {
  // 8文字～64文字でなければ早期に不合格
  const minLength = 8;
  const maxLength = 64;
  if (password.length < minLength || password.length > maxLength) return false;

  // 英字の大文字、英字の小文字、アラビア数字、記号（@#$%^&*\-_+=[]{}|\:',.?/`~"();!）から2種類以上組み合わせ
  const charaTypePattern =
    // eslint-disable-next-line no-useless-escape
    /^((?=.*[a-z])(?=.*[A-Z])|(?=.*[a-z])(?=.*[\d])|(?=.*[a-z])(?=.*[@#$%^&*\\\-_+=\[\]{}|:',.?\/`~"();!])|(?=.*[A-Z])(?=.*[\d])|(?=.*[A-Z])(?=.*[@#$%^&*\\\-_+=\[\]{}|:',.?\/`~"();!])|(?=.*[\d])(?=.*[@#$%^&*\\\-_+=\[\]{}|:',.?\/`~"();!]))[a-zA-Z\d@#$%^&*\\\-_+=\[\]{}|:',.?\/`~"();!]/;
  return new RegExp(charaTypePattern).test(password);
};

// Account Info
export const selectCompany = (state: RootState) => state.signup.apps.company;
export const selectCountry = (state: RootState) => state.signup.apps.country;
export const selectDealer = (state: RootState) => state.signup.apps.dealer;

// Admin Info
export const selectAdminName = (state: RootState) =>
  state.signup.apps.adminName;
export const selectEmail = (state: RootState) => state.signup.apps.email;
export const selectPassword = (state: RootState) => state.signup.apps.password;

export const selectPageState = (state: RootState) =>
  state.signup.apps.pageState;
