import { Assignee } from "api";
import { RootState } from "app/store";

export const selectWorkflows = (state: RootState) =>
  state.workflow.domain.workflows;

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

export const selectWorkflowRelations = (state: RootState) =>
  state.workflow.domain.workflowRelations;

export const selectWorkflowAssinee = (state: RootState) => {
  // 選択されたassigneeを取得
  const { selectedAssignees } = state.workflow.apps;
  // すべてのassigneeを取得
  const assignees = state.workflow.domain.workflowRelations?.assignees ?? [];
  // assigneeが選択されているかどうかを判定する
  const isAssigneeSelected = (assignee: Assignee) =>
    selectedAssignees.some(
      (sa) =>
        sa.typistUserId === assignee.typistUserId &&
        sa.typistGroupId === assignee.typistGroupId
    );
  // 未選択のassigneeを取得する
  const poolAssignees = assignees.filter(
    (assignee) => !isAssigneeSelected(assignee)
  );
  // selectedAssigneesとpoolAssigneesをtypistNameでソートして返す
  return {
    selectedAssignees: [...selectedAssignees].sort((a, b) =>
      a.typistName.localeCompare(b.typistName)
    ),
    poolAssignees: poolAssignees.sort((a, b) =>
      a.typistName.localeCompare(b.typistName)
    ),
  };
};
export const selectSelectedWorkflow = (state: RootState) =>
  state.workflow.apps.selectedWorkflow;
export const selectAuthorId = (state: RootState) =>
  state.workflow.apps.authorId;
export const selectWorktypeId = (state: RootState) =>
  state.workflow.apps.worktypeId;
export const selectTemplateId = (state: RootState) =>
  state.workflow.apps.templateId;

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

export const selectWorkflowError = (state: RootState) => {
  // authorIdがundefinedの場合はエラーを返す
  const hasAuthorIdEmptyError = state.workflow.apps.authorId === undefined;
  // workflowAssineeのselectedが空の場合はエラーを返す
  const hasSelectedWorkflowAssineeEmptyError =
    state.workflow.apps.selectedAssignees.length === 0;
  return {
    hasAuthorIdEmptyError,
    hasSelectedWorkflowAssineeEmptyError,
  };
};
