"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useFieldFormatter = void 0;
var _react = require("react");
var _services = require("../services");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const useFieldFormatter = ({
  dataViewId,
  fieldSpec
}) => {
  const {
    dataViews: {
      get: getDataViewById
    }
  } = _services.pluginServices.getServices();
  const [fieldFormatter, setFieldFormatter] = (0, _react.useState)(() => toFormat => toFormat);

  /**
   * derive field formatter from fieldSpec and dataViewId
   */
  (0, _react.useEffect)(() => {
    (async () => {
      if (!dataViewId || !fieldSpec) return;
      // dataViews are cached, and should always be available without having to hit ES.
      const dataView = await getDataViewById(dataViewId);
      setFieldFormatter(() => {
        var _dataView$getFormatte;
        return (_dataView$getFormatte = dataView === null || dataView === void 0 ? void 0 : dataView.getFormatterForField(fieldSpec).getConverterFor('text')) !== null && _dataView$getFormatte !== void 0 ? _dataView$getFormatte : toFormat => toFormat;
      });
    })();
  }, [fieldSpec, dataViewId, getDataViewById]);
  return fieldFormatter;
};
exports.useFieldFormatter = useFieldFormatter;