import { OptionMenu } from '@/manager/shared/components/OptionMenu';
import { BaseComponent } from '@/shared/base/BaseComponent';
import { getCount } from '@/shared/utils/locator-utils';
import { isString } from 'lodash';

export class MultiAutocomplete extends BaseComponent {
  private readonly body = this.host.locator('.v-field');
  private readonly input = this.body.locator('input');
  private readonly closeButtons = this.body.locator('.mdi-close-circle');
  private readonly progressBar = this.body.getByRole('progressbar');
  private readonly menu = new OptionMenu(this.input);

  async select(values: string | string[]): Promise<void> {
    const options = isString(values) ? [values] : values;
    await this.progressBar.waitFor({ state: 'hidden' });
    await this.clear();

    for (const option of options) {
      await this.input.type(option);
      await this.menu.select(option);
      await this.input.clear();
    }

    await this.input.press('Escape');
  }

  async fill(values: string | string[]): Promise<void> {
    const options = isString(values) ? [values] : values;
    await this.progressBar.waitFor({ state: 'hidden' });
    await this.clear();

    for (const option of options) {
      await this.input.type(option);
      await this.input.press('Enter');
      await this.input.clear();
    }

    await this.input.press('Escape');
  }

  async clear(): Promise<void> {
    const numberOfButtons = await getCount(this.body, this.closeButtons);

    for (let index = 0; index < numberOfButtons; index++) {
      await this.closeButtons.nth(numberOfButtons - (index + 1)).click();
    }
  }
}
