"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchKeyByFilter = void 0;
const oj_module_proxy_1 = require("./oj-module-proxy");
/**
 * Get the key for the record filtered by filterDef. If exactly one record is
 * found after filtering is applied, the key of that record is returned.
 * An error is thrown if, after filtering:
 * - no records are found
 * - more than one record is found
 * If the property identified by dataProviderProp doesn't exist or is not a DataProvider,
 * an error will be also thrown.
 * @typeParam E - Custom element type
 * @typeParam K - Type of key value
 * @typeParam DataProviderProps - Type representing DataProvider-valued properties of the custom element type
 * @param el The OjWebElement whose properties reference the DataProvider
 * @param dataProviderProp The property name within the element identifying the DataProvider
 * @param filterDef A [FilterDef](https://www.oracle.com/webfolder/technetwork/jet/jsdocs/DataFilter.html#FilterDef)
 * used to locate the record within the DataProvider
 * @return {K} The key of the matching record
 *
 * #### Example Usage
 * Fetch a key from a SelectSingle DataProvider by filtering for a DepartmentName
 * ```javascript
 * import { fetchKeyByFilter } from '@oracle/oraclejet-webdriver';
 * import { ojSelectSingle as JetSelectSingle } from '@oracle/oraclejet/ojselectsingle';

 * const ss1 = await ojSelectSingle(driver, By.id('department-select'));
 * const key = fetchKeyByFilter<JetSelectSingle<string,any>,string>(ss1, 'data', {
 *   op: '$eq',
 *   value: { DepartmentName: 'Finance' }
 * });
 * await ss1.changeValue(key);
 * ```
 */
async function fetchKeyByFilter(el, dataProviderProp, filterDef) {
    await el.whenBusyContextReady();
    return (0, oj_module_proxy_1.executeWithModules)(el.getDriver(), ['CustomElementUtils'], [el, dataProviderProp, filterDef], `
    (({ getElementProperty }, comp, dataProviderProp, filterDef) => {
      return new Promise((resolve, reject) => {

        const dp = getElementProperty(comp, dataProviderProp);
        if (!(dp && typeof dp.fetchFirst === 'function')) {
          reject('Property "${dataProviderProp}" does not reference a supported DataProvider');
        }

        const iter = dp.fetchFirst({
          filterCriterion: filterDef
        })[Symbol.asyncIterator]();

        iter.next().then(res => {
          if (res.value.metadata.length === 1) {
            resolve(res.value.metadata[0].key);
          }
          else if (res.value.metadata.length > 1) {
            reject('Filter returned too many keys: ' + res.value.metadata.map(r => r.key));
          }
          else {
            reject('Filter returned no keys');
          }
        });
      });

    })
  `);
}
exports.fetchKeyByFilter = fetchKeyByFilter;
//# sourceMappingURL=dataprovider-utils.js.map