"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useAppDataView = void 0;
var _react = require("react");
var _public = require("@kbn/observability-shared-plugin/public");
var _use_local_data_view = require("./use_local_data_view");
var _observability_data_views = require("../../../../utils/observability_data_views/observability_data_views");
/*
 * 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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const useAppDataView = ({
  series,
  dataViewCache,
  seriesDataType,
  dataViewsService,
  dataTypesIndexPatterns
}) => {
  const [dataViews, setDataViews] = (0, _react.useState)({});
  const {
    dataViewTitle
  } = (0, _use_local_data_view.useLocalDataView)(seriesDataType, dataTypesIndexPatterns);
  const {
    loading
  } = (0, _public.useFetcher)(async () => {
    if (dataViewTitle && !dataViews[seriesDataType]) {
      if (dataViewCache[dataViewTitle]) {
        setDataViews(prevState => ({
          ...(prevState !== null && prevState !== void 0 ? prevState : {}),
          [seriesDataType]: dataViewCache[dataViewTitle]
        }));
      } else {
        const obsvIndexP = new _observability_data_views.ObservabilityDataViews(dataViewsService, true);
        const indPattern = await obsvIndexP.getDataView(seriesDataType, dataViewTitle);
        dataViewCache[dataViewTitle] = indPattern;
        setDataViews(prevState => ({
          ...(prevState !== null && prevState !== void 0 ? prevState : {}),
          [seriesDataType]: indPattern
        }));
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataViewTitle, seriesDataType, JSON.stringify(series)]);
  return {
    dataViews,
    loading: loading && !dataViews[seriesDataType]
  };
};
exports.useAppDataView = useAppDataView;