import { RootState } from "app/store";

export const selectWorktypes = (state: RootState) =>
  state.worktype.domain.worktypes;

export const selectIsLoading = (state: RootState) =>
  state.worktype.apps.isLoading;

export const selectIsAddLoading = (state: RootState) =>
  state.worktype.apps.isAddLoading;

export const selectIsEditLoading = (state: RootState) =>
  state.worktype.apps.isEditLoading;

export const selectSelectedId = (state: RootState) =>
  state.worktype.apps.selectedId;

export const selectWorktypeId = (state: RootState) =>
  state.worktype.apps.worktypeId;

export const selectDescription = (state: RootState) =>
  state.worktype.apps.description;

// worktypeIdの値をチェックする
export const selectHasErrorWorktypeId = (state: RootState) => {
  const { worktypeId } = state.worktype.apps;
  // worktypeIdが空文字の場合はエラー
  const isEmptyWorktypeId = worktypeId === "";

  // worktypeIdに\/ : * ? “< > | .が含まれている場合はエラー
  const incorrectPattern = /[\\/:*?"<>|.]|[^ -~]/;
  const hasIncorrectPatternWorktypeId = incorrectPattern.test(worktypeId);

  return { isEmptyWorktypeId, hasIncorrectPatternWorktypeId };
};

export const selectOptionItems = (state: RootState) =>
  state.worktype.apps.optionItems;

// OptionItemsの値をチェックする
export const selectHasErrorOptionItems = (state: RootState) => {
  const { optionItems } = state.worktype.apps;
  if (!optionItems) {
    return {
      hasInvalidOptionItems: false,
      hasIncorrectPatternOptionItems: false,
    };
  }
  // optionItemsに以下の状態の要素が含まれている場合はエラー
  // itemLabelに値が入っている
  // defaultValueTypeがDefault
  // initialValueに値が入っていない
  const hasInvalidOptionItems = optionItems.some(
    (item) =>
      item.itemLabel !== "" &&
      item.defaultValueType === "Default" &&
      item.initialValue === ""
  );
  // optionItemsに以下の状態の要素が含まれている場合はエラー
  // itemLabelとinitialValueのどちらかに\/ : * ? “< > | .が含まれている
  const incorrectPattern = /[\\/:*?"<>|.]|[^ -~]/;
  const hasIncorrectPatternOptionItems = optionItems.some(
    (item) =>
      incorrectPattern.test(item.itemLabel) ||
      incorrectPattern.test(item.initialValue)
  );
  return { hasInvalidOptionItems, hasIncorrectPatternOptionItems };
};

// isOptionItemsLoadingを取得する
export const selectIsOptionItemsLoading = (state: RootState) =>
  state.worktype.apps.isOptionItemsLoading;

export const selectActiveWorktypeId = (state: RootState) =>
  state.worktype.apps.activeWorktypeId;
