import type { FileTreeSelectionState } from "./selection";

export type FileTreeSelectionSnapshotPayload = {
  selectedRowIds: readonly string[];
  anchorRowId: string | null;
  focusedRowId: string | null;
};

export function createEmptyFileTreeSelectionState(): FileTreeSelectionState {
  return {
    selectedRowIds: new Set<string>(),
    anchorRowId: null,
    focusedRowId: null,
  };
}

export function materializeRendererSelectionSnapshot(input: {
  payload: FileTreeSelectionSnapshotPayload;
  hasRowId: (rowId: string) => boolean;
}): FileTreeSelectionState {
  const selectedRowIds = new Set(
    input.payload.selectedRowIds.filter((rowId) => input.hasRowId(rowId)),
  );

  return {
    selectedRowIds,
    anchorRowId:
      input.payload.anchorRowId && input.hasRowId(input.payload.anchorRowId)
        ? input.payload.anchorRowId
        : null,
    focusedRowId:
      input.payload.focusedRowId && input.hasRowId(input.payload.focusedRowId)
        ? input.payload.focusedRowId
        : null,
  };
}

export function resolveActiveFileTreeSelection(input: {
  preferRendererSnapshot: boolean;
  legacySelection: FileTreeSelectionState;
  rendererSelection: FileTreeSelectionState;
}): FileTreeSelectionState {
  return input.preferRendererSnapshot
    ? input.rendererSelection
    : input.legacySelection;
}
