/* eslint-disable react/destructuring-assignment, no-console, max-len */

import React, { useContext, useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { List, Card } from 'antd';

// import { contexts as PageContext, ddRender } from '@db-man/components';
import PageContext from '../contexts/page';
import * as ddRender from '../ddRender/ddRender';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const listGrid = {
  gutter: 16,
  xs: 1,
  sm: 2,
  md: 4,
  lg: 4,
  // ≥992px column of grid
  xl: 4,
  // ≥1200px column of grid
  xxl: 4 // ≥1600px column of grid
};

const defaultPageSize = 8;
const getAny = arr => arr[Math.floor(Math.random() * arr.length)];
export const getRandomItems = rows => {
  const randomItems = [];
  const numberOfItems = Math.min(defaultPageSize, rows.length);
  for (let i = 0; i < numberOfItems; i += 1) {
    randomItems.push(getAny(rows));
  }
  return randomItems;
};
export default function RandomList({
  rows
}) {
  const {
    dbName,
    tableName,
    primaryKey,
    columns
  } = useContext(PageContext);

  // idx only used to force reload page data
  const [idx, setIdx] = useState(0);

  // Press `r` to reload page data
  useEffect(() => {
    const onKeyDown = event => {
      if (event.key === 'r') {
        // idx only used to force rerender this component
        setIdx(idx + 1);
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [idx]);

  // idx only used to force reload page data

  const renderItem = item => {
    const column = columns.find(col => col.id === primaryKey);
    if (!column) return /*#__PURE__*/_jsx("div", {
      children: "No primary column found"
    });
    const args = column['ui:listPage:randomView'] || '';
    const fn = ddRender.getRender(args) || (val => val);
    return /*#__PURE__*/_jsx(List.Item, {
      children: /*#__PURE__*/_jsxs(Card, {
        children: [/*#__PURE__*/_jsx("div", {
          children: item[primaryKey]
        }), /*#__PURE__*/_jsx("div", {
          children: fn(item[primaryKey], item, 0)
        }), /*#__PURE__*/_jsx(Link, {
          to: {
            pathname: `/${dbName}/${tableName}/update`,
            search: `?${primaryKey}=${item[primaryKey]}`
          },
          children: "Update"
        })]
      })
    });
  };
  if (!rows) return null;
  return /*#__PURE__*/_jsx(List, {
    grid: listGrid,
    dataSource: getRandomItems(rows),
    renderItem: renderItem
  });
}
//# sourceMappingURL=RandomList.js.map