"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useActiveCursor = void 0;
var _lodash = require("lodash");
var _rxjs = require("rxjs");
var _react = require("react");
var _operators = require("rxjs/operators");
var _active_cursor_utils = require("./active_cursor_utils");
/*
 * 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 DEFAULT_DEBOUNCE_TIME = 40;
const useActiveCursor = (activeCursor, chartRef, syncOptions) => {
  const {
    accessors,
    isDateHistogram
  } = (0, _active_cursor_utils.parseSyncOptions)(syncOptions);
  const handleCursorUpdate = (0, _react.useCallback)(cursor => {
    var _activeCursor$activeC;
    (_activeCursor$activeC = activeCursor.activeCursor$) === null || _activeCursor$activeC === void 0 ? void 0 : _activeCursor$activeC.next({
      cursor,
      isDateHistogram,
      accessors
    });
  }, [activeCursor.activeCursor$, accessors, isDateHistogram]);
  (0, _react.useEffect)(() => {
    var _activeCursor$activeC2, _syncOptions$debounce;
    const cursorSubscription = (_activeCursor$activeC2 = activeCursor.activeCursor$) === null || _activeCursor$activeC2 === void 0 ? void 0 : _activeCursor$activeC2.pipe((0, _operators.debounceTime)((_syncOptions$debounce = syncOptions.debounce) !== null && _syncOptions$debounce !== void 0 ? _syncOptions$debounce : DEFAULT_DEBOUNCE_TIME, _rxjs.animationFrameScheduler), (0, _operators.filter)(payload => {
      if (payload.isDateHistogram && isDateHistogram) {
        return true;
      }
      return (0, _lodash.intersection)(accessors, payload.accessors).length > 0;
    })).subscribe(({
      cursor
    }) => {
      var _chartRef$current;
      chartRef === null || chartRef === void 0 ? void 0 : (_chartRef$current = chartRef.current) === null || _chartRef$current === void 0 ? void 0 : _chartRef$current.dispatchExternalPointerEvent(cursor);
    });
    return () => {
      cursorSubscription === null || cursorSubscription === void 0 ? void 0 : cursorSubscription.unsubscribe();
    };
  }, [activeCursor.activeCursor$, syncOptions.debounce, chartRef, accessors, isDateHistogram]);
  return handleCursorUpdate;
};
exports.useActiveCursor = useActiveCursor;