import {getDatabase} from './getDB';
import {databaseConf, mergeDBName, possibleDBKeys} from './types';

export interface filterParam {
  type: 'name';
}

export const getEntry = async <T2 extends databaseConf<T, any>, T>(
  schema: T2,
  key: possibleDBKeys,
  suffix?: string,
): Promise<null | T> => {
  const nameObj = {name: schema.details.name, suffix};
  const dbName = mergeDBName(nameObj);

  const realm = await getDatabase(nameObj);

  const val = realm.objectForPrimaryKey<typeof schema.details.properties>(
    nameObj.name,
    key,
  );

  return val as T;
};

export const getAllEntries = async <T2 extends databaseConf<T, any>, T>(
  schema: T2,
  filter?: filterParam,
  suffix?: string,
): Promise<null | T[]> => {
  const nameObj = {name: schema.details.name, suffix};
  const dbName = mergeDBName(nameObj);

  const realm = await getDatabase(nameObj);

  const val = realm.objects<typeof schema.details.properties>(nameObj.name);

  return [...val] as T[];
};
