import { OjSelectSingleBase } from './OjSelectSingleBase';
import { executeWithModules } from '../../lib/oj-module-proxy';

/**
 * The component WebElement for [oj-select-single](../../jsdocs/oj.ojSelectSingle.html).
 * Do not instantiate this class directly, instead, use
 * [ojSelectSingle](../functions/elements.ojSelectSingle-1.html).
 */
export class OjSelectSingle extends OjSelectSingleBase {
  /**
   * Sets the value of "value" property.
   * The value of the element.
   * @param value The value to set for "value"
   * @override
   */
  async changeValue(value: any) {
    // Call focus() on the root element
    await this.getDriver().executeScript('arguments[0].focus()', this);
    // Only mutate if not readonly/disabled
    const readonly = await this.getReadonly();
    const disabled = await this.getDisabled();
    if (!(readonly || disabled)) {
      await this.whenBusyContextReady();
      return executeWithModules<void>(
        this.getDriver(),
        ['CustomElementUtils'],
        [this, value],
        `
        (({ getElementBridge }, element, value) => {
          // Retrieve the widget instance from the element
          var bridge = getElementBridge(element);
          var widget = bridge._WIDGET_INSTANCE;
          return widget._selectItemByValue(value);
        })
      `
      );
    }
  }

  /**
   * Clears the value
   * @override
   */
  clear(): Promise<void> {
    return this.changeValue(null);
  }
}
