import { OjStreamListBase } from './OjStreamListBase';
import { By, WebElement } from 'selenium-webdriver';

/**
 * The component WebElement for [oj-stream-list](../../jsdocs/oj.ojStreamList.html).
 * Do not instantiate this class directly, instead, use
 * [ojStreamList](../functions/elements.ojStreamList-1.html).
 */
export class OjStreamList extends OjStreamListBase {
  // Put overrides here
  async findItem<T>(itemLocator: { key?: T; parentKey?: T }): Promise<WebElement> {
    const items = await this.findElements(By.css('.oj-stream-list-item, .oj-stream-list-group'));
    await this.whenBusyContextReady();
    return this.getDriver().executeScript(
      `
    let el;
    var element = arguments[0];
    var key = arguments[1].key;
    var parentKey = arguments[1].parentKey;
    var items = arguments[2];
    var getParentKey = function (item) {
      while (item) {
        if (item.classList.contains('oj-stream-list-group')) {
          return item.dataset.ojKey;
        }
        item = item.previousElementSibling;
      }
      return null;
    }
    for (let i = 0; i < items.length; i++) {
      let item = items[i];
      let itemKey = item.dataset.ojKey;
      if (itemKey == key) {
        if (parentKey == null || getParentKey(item) == parentKey) {
          el = item;
        }
      }
    }
    return el;
    `,
      this,
      itemLocator,
      items
    );
  }

  async findGroup<T>(itemLocator: { key?: T }): Promise<WebElement> {
    const items = await this.findElements(By.css('.oj-stream-list-group'));
    await this.whenBusyContextReady();

    let group = await this.getDriver().executeAsyncScript<WebElement>(
      `
    let el;
    let index;
    var element = arguments[0];
    var key = arguments[1].key;
    var items = arguments[2];
    for (let i = 0; i < items.length; i++) {
      let item = items[i];
      let itemKey = item.dataset.ojKey;
      if (itemKey == key) {
        index = i;
        el = item;
      }
    }
    return el;
    `,
      this,
      itemLocator,
      items
    );

    return group;
  }
}
