import { DataType, StringUtils } from "@sankhyalabs/core";
import { DataFetcher } from "../../../DataFetcher";
import { gql } from "graphql-request";
const GQL_QUERY = gql `query($dataunit: String! $limit: Int $offset:Int $filters: [InputFilter!] $sort: [InputSort!] $parentRecordId: String) {
    $queryAlias$: fetchDataUnit(name: $dataunit) {
      data(limit: $limit offset: $offset filters: $filters sort: $sort parentRecordId: $parentRecordId) {
        limit
        offset
        total
        hasMore
        records {
          id
          label
          fields {
            name
            value
          }
        }
      }
    }
  }`;
export class DataUnitStrategy {
  canSlice() {
    return true;
  }
  getVariables(dataunit, request) {
    var _a;
    let { sort, filters, limit, offset, quickFilter, parentRecordId } = request;
    if (!StringUtils.isEmpty(quickFilter === null || quickFilter === void 0 ? void 0 : quickFilter.term)) {
      const quickFilterCriteria = {
        name: "__QUICK_FILTER__",
        expression: "__QUICK_FILTER__",
        params: [{ name: "term", dataType: DataType.TEXT, value: quickFilter.term }]
      };
      if (((_a = quickFilter.fields) === null || _a === void 0 ? void 0 : _a.length) > 0) {
        quickFilterCriteria.params.push({ name: "fields", dataType: DataType.OBJECT, value: quickFilter.fields });
      }
      if (filters === undefined) {
        filters = [];
      }
      filters.push(quickFilterCriteria);
    }
    return { dataunit, sort, filters, limit, offset, parentRecordId };
  }
  async load(dataUnit, request, loadingInfo) {
    return new Promise((accept, reject) => {
      DataFetcher.get().callGraphQL({
        values: this.getVariables(dataUnit.name, request),
        query: GQL_QUERY
      }, false)
        .then(resp => {
        const { hasMore, records: responseRecords, total } = resp.data;
        const records = responseRecords.map((record) => {
          const duRecord = { __record__id__: record.id, __record__label__: record.label };
          record.fields.forEach(({ name, value }) => {
            duRecord[name] = dataUnit.valueFromString(name, value);
          });
          return duRecord;
        });
        accept({
          records,
          loadingInfo: Object.assign(Object.assign({}, loadingInfo), { loadingInProgress: hasMore, total, count: loadingInfo.count + records.length })
        });
      })
        .catch(reason => reject(reason));
    });
  }
}
