import { SimpleCheckbox } from '@/manager/shared/components/SimpleCheckbox';
import { BaseComponent } from '@/shared/base/BaseComponent';
import { Locator } from '@playwright/test';

export class DataTableRowSelector extends BaseComponent {
  private readonly selectOneCheckboxes = this.host.getByTestId('ui-data-grid-cell-select');
  private readonly selectAllCheckbox = this.host.getByTestId('ui-data-grid-header-select-all');

  reset(): Promise<void> {
    return this.clickAction('reset');
  }

  // Action-bar test ids also land on a wrapper div, so the button element is targeted explicitly.
  getAction(actionTestId: string): Locator {
    return this.host.locator(`button[data-test-id="${actionTestId}"]`);
  }

  clickAction(actionTestId: string): Promise<void> {
    return this.getAction(actionTestId).click();
  }

  selectAll(): Promise<void> {
    return this.checkAll(true);
  }

  async deselectAll(): Promise<void> {
    await this.checkAll(true);
    return this.checkAll(false);
  }

  select(indexes: number | number[]): Promise<void> {
    return this.check(indexes, true);
  }

  deselect(indexes: number | number[]): Promise<void> {
    return this.check(indexes, false);
  }

  private async checkAll(checking: boolean): Promise<void> {
    const checkbox = new SimpleCheckbox(this.selectAllCheckbox);
    return checkbox.set(checking);
  }

  private async check(indexes: number | number[], checking: boolean): Promise<void> {
    const indexesArray = typeof indexes === 'number' ? [indexes] : indexes;

    for (const index of indexesArray) {
      const checkbox = new SimpleCheckbox(this.selectOneCheckboxes.nth(index));
      await checkbox.set(checking);
    }
  }
}
