import { DEFAULT_ROWS_PER_PAGE, ROWS_PER_PAGE_OPTIONS } from '../../common/Pagination';
import { ROWS_PER_PAGE_KEY, SORTABLE_COLUMNS } from '../constants';
import type { GroupType, SortState } from '../types';

// Personal groups sort by name, shared ones by priority.
export const defaultSortColumn = (type: GroupType) => (type === 'shared' ? 'priority' : 'name');

const readStoredRowsPerPage = (): number => {
  const stored = Number(window.localStorage.getItem(ROWS_PER_PAGE_KEY));
  return ROWS_PER_PAGE_OPTIONS.includes(stored) ? stored : DEFAULT_ROWS_PER_PAGE;
};

export const storeRowsPerPage = (value: number): void => window.localStorage.setItem(ROWS_PER_PAGE_KEY, String(value));

export interface ListParams {
  page: number;
  rowsPerPage: number;
  sort: SortState;
}

// The list view state lives in the query string so a reload or shared link
// lands on the same page; anything unusable falls back to the default.
export const readListParams = (params: URLSearchParams, type: GroupType): ListParams => {
  const page = Math.max(1, Math.trunc(Number(params.get('page'))) || 1);
  const perPage = Number(params.get('perPage'));
  const column = params.get('sortColumn');
  return {
    page,
    rowsPerPage: ROWS_PER_PAGE_OPTIONS.includes(perPage) ? perPage : readStoredRowsPerPage(),
    sort: {
      column: column && SORTABLE_COLUMNS.includes(column) ? column : defaultSortColumn(type),
      descending: params.get('sortDescending') === 'true'
    }
  };
};
