import { SimpleCheckbox } from '@/manager/shared/components/SimpleCheckbox';
import { BaseComponent } from '@/shared/base/BaseComponent';
import { isNumber } from 'lodash';

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');
  }

  clickAction(actionTestId: string): Promise<void> {
    const action = this.host.locator(`button[data-test-id="${actionTestId}"]`);
    return action.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 = isNumber(indexes) ? [indexes] : indexes;

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