"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useMarkdownSessionStorage = void 0;
var _react = require("react");
var _lodash = require("lodash");
var _useDebounce = _interopRequireDefault(require("react-use/lib/useDebounce"));
var _useSessionStorage = _interopRequireDefault(require("react-use/lib/useSessionStorage"));
/*
 * 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 STORAGE_DEBOUNCE_TIME = 500;
const useMarkdownSessionStorage = ({
  field,
  sessionKey,
  initialValue
}) => {
  const [hasConflicts, setHasConflicts] = (0, _react.useState)(false);
  const isFirstRender = (0, _react.useRef)(true);
  const initialValueRef = (0, _react.useRef)(initialValue);
  const [sessionValue, setSessionValue] = (0, _useSessionStorage.default)(sessionKey, '', true);
  if (!(0, _lodash.isEmpty)(sessionValue) && isFirstRender.current) {
    field.setValue(sessionValue);
  }
  if (isFirstRender.current) {
    isFirstRender.current = false;
  }
  if (initialValue !== initialValueRef.current && initialValue !== field.value) {
    initialValueRef.current = initialValue;
    setHasConflicts(true);
  }
  (0, _useDebounce.default)(() => {
    setSessionValue(field.value);
  }, STORAGE_DEBOUNCE_TIME, [field.value]);
  return {
    hasConflicts
  };
};
exports.useMarkdownSessionStorage = useMarkdownSessionStorage;