import { DataResult, GroupDescriptor } from "@progress/kendo-data-query";
import {
  GridColumnResizeEvent,
  GridHeaderSelectionChangeEvent,
  GridSelectionChangeEvent,
} from "@progress/kendo-react-grid";
import _ from "lodash";

export const handleSelectionChange = (
  event: GridSelectionChangeEvent,
  baseData: any,
  selectedField: string | undefined = "",
  resultHandler: (data: any) => void
) => {
  const modifiedBaseData = event.dataItems?.map((dataItem: any) => {
    if (dataItem === event.dataItem) {
      dataItem = {
        ...dataItem,
        [selectedField]: dataItem[selectedField] ? false : true,
      };
    }
    return dataItem;
  });
  baseData.records = modifiedBaseData;
  resultHandler(baseData);
};

export const handleHeaderSelectionChange = (
  event: GridHeaderSelectionChangeEvent,
  baseData: any,
  selectedField: string | undefined = "",
  dataResult: DataResult,
  resultHandler: (data: any) => void
) => {
  const selectedCount = baseData.records.filter(
    (r: any) => r[selectedField ?? ""] === true
  ).length;
  const isAllSelected = selectedCount === dataResult.total;
  const modifiedBaseData = event.dataItems?.map((dataItem: any) => {
    dataItem = {
      ...dataItem,
      [selectedField]: !isAllSelected,
    };
    return dataItem;
  });
  baseData.records = modifiedBaseData;
  resultHandler(baseData);
};

export const markAllDataAsSelected = (
  baseData: any,
  selectedField: string | undefined = "",
  resultHandler: (data: any) => void
) => {
  const modifiedBaseData = baseData.records?.map((record: any) => {
    record = { ...record, [selectedField ?? ""]: true };
    return record;
  });

  resultHandler({ ...baseData, records: modifiedBaseData });
};

export const unMarkAllDataAsUnSelected = (
  baseData: any,
  selectedField: string | undefined = "",
  resultHandler: (data: any) => void
) => {
  const modifiedBaseData = baseData.records?.map((record: any) => {
    record = { ...record, [selectedField ?? ""]: false };
    return record;
  });

  resultHandler({ ...baseData, records: modifiedBaseData });
};

export const deserializedGroupFilelds = (
  appliedGroups: { label: string; value: string }[],
  defaultGroups: GroupDescriptor[]
): GroupDescriptor[] => {
  let groupDescriptors: GroupDescriptor[] = [];
  if (appliedGroups?.length) {
    appliedGroups.forEach((group) => {
      groupDescriptors.push({ field: group.value, dir: "asc" });
    });
  } else {
    groupDescriptors = defaultGroups;
  }

  return groupDescriptors;
};
