import { OjSwitchBase } from './OjSwitchBase';
import { By, error, Key } from 'selenium-webdriver';

/**
 * The component WebElement for [oj-switch](../../jsdocs/oj.ojSwitch.html).
 * Do not instantiate this class directly, instead, use
 * [ojSwitch](../functions/elements.ojSwitch-1.html).
 */
export class OjSwitch extends OjSwitchBase {
  /**
   * Sets the value of "value" property.
   * The boolean state of the switch component.
   * @param value The value to set for "value"
   */
  async changeValue(value: boolean): Promise<void> {
    // Check if the control is interactable
    if (!(await this.isInteractable())) {
      // Cannot interact when the control is disabled or readonly
      return Promise.reject(
        new error.ElementNotInteractableError(
          'OjSwitch: Value cannot be changed when the control is disabled or readonly'
        )
      );
    }

    // Call focus() on the root element
    await this.getDriver().executeScript('arguments[0].focus()', this);

    const isChecked = (await this.getAttribute('class')).split(' ').includes('oj-selected');
    if (value !== isChecked) {
      await this.findElement(By.css('.oj-switch-thumb')).sendKeys(Key.SPACE);
    }
  }

  /**
   * Checks if the Switch is in interactable state
   */
  private async isInteractable(): Promise<boolean> {
    const isReadonly = await this.getReadonly();
    const isDisabled = await this.getDisabled();
    return !(isReadonly || isDisabled);
  }
}
