import { Dispatch, FC, SetStateAction } from "react";
import { SlickDataView } from "slickgrid";

import { eventContextMenu } from "shared/lib/slickgrid";
import { IEditedRow, ISlickRow } from "shared/model/types";

import Styled from "../ContextMenu.style";

export const CopyRows: FC<IProps> = ({ setIsOpened }) => {
	const table = eventContextMenu.table;
	const grid = table?.grid;
	const selectedRows = grid?.getSelectedRows();

	function copyRows() {
		if (!grid || !table || !selectedRows) {
			return;
		}
		const dataView: SlickDataView = grid.getData();
		const result: (ISlickRow & IEditedRow)[] = [];
		for (let i = 0; i < selectedRows.length; i++) {
			result.push(dataView.getItem(selectedRows[i]));
		}
		table.copiedRows = result;
		grid.setSelectedRows([]);
		setIsOpened(false);
	}

	if (!selectedRows?.length) return null;

	return (
		<Styled.Li onClick={copyRows}>
			<Styled.Icon className={"sgi sgi-content-copy"}></Styled.Icon>Copy
			selected rows
		</Styled.Li>
	);
};

interface IProps {
	setIsOpened: Dispatch<SetStateAction<boolean>>;
}
