import { GridSelectionColumn } from '@vaadin/grid/vaadin-grid-selection-column';

const createCheckboxEle = () => {
  const checkbox = document.createElement('descope-checkbox');

  checkbox.setAttribute('bordered', 'true');
  checkbox.setAttribute('size', 'xs');

  return checkbox;
};

const getIsAllItemsSelected = (grid) =>
  !!grid.items?.length && grid.selectedItems.length === grid.items.length;

export class GridSelectionColumnClass extends GridSelectionColumn {
  // eslint-disable-next-line class-methods-use-this
  _onHeaderRendererOrBindingChanged() {}

  // eslint-disable-next-line class-methods-use-this
  _headerRenderer(cell) {
    const grid = cell.parentNode;

    let checkbox = cell.querySelector('descope-checkbox');
    if (!checkbox) {
      checkbox = createCheckboxEle();

      checkbox.addEventListener('input', () => {
        const isAllItemsSelected = getIsAllItemsSelected(grid);
        if (isAllItemsSelected) {
          grid.selectedItems = [];
        } else {
          grid.selectedItems = grid.items;
        }
      });

      cell.appendChild(checkbox);
    }

    checkbox.setAttribute('checked', getIsAllItemsSelected(grid));
  }

  // eslint-disable-next-line class-methods-use-this
  _defaultRenderer(cell, col, model) {
    const grid = cell.parentNode;

    let checkbox = cell.querySelector('descope-checkbox');
    if (!checkbox) {
      checkbox = createCheckboxEle();
      cell.appendChild(checkbox);
    }

    checkbox.onchange = () => {
      checkbox.checked ? grid.selectItem(model.item) : grid.deselectItem(model.item);
    };

    checkbox.setAttribute('checked', model.selected);
  }
}
