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

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

  async select(values: string | string[]): Promise<void> {
    const options = typeof values === 'string' ? [values] : values;
    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 = typeof values === 'string' ? [values] : values;
    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();
    }
  }
}
