import { Chance } from 'chance';
import {
  InMemoryBackend,
  InMemoryBackendParams,
} from '@wix/bex-core/in-memory-backend';
import { Site } from './site';
import escapeRegExp from 'lodash/escapeRegExp';

export const createSitesBackend = (
  params?: Partial<InMemoryBackendParams<Site, {}>>,
) => {
  const chance = new Chance();

  return new InMemoryBackend<Site>({
    createOne: () => ({
      id: chance.guid(),
      name: chance.string(),
      thumbnail: chance.avatar(),
      viewUrl: chance.url(),
    }),
    itemKey: (item) => item.id,
    total: 1000,
    predicate: ({ search }) => {
      const rgx = new RegExp(escapeRegExp(search), 'i');

      return (item) => {
        if (search && !rgx.test(item.name)) {
          return false;
        }

        return true;
      };
    },
    ...params,
  });
};
