"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useWorkpadPersist = void 0;
var _react = require("react");
var _usePrevious = _interopRequireDefault(require("react-use/lib/usePrevious"));
var _reactRedux = require("react-redux");
var _workpad = require("../../../state/selectors/workpad");
var _app = require("../../../state/selectors/app");
var _services = require("../../../services");
var _assets = require("../../../lib/assets");
/*
 * 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 useWorkpadPersist = () => {
  const service = (0, _services.useWorkpadService)();
  const notifyService = (0, _services.useNotifyService)();

  // Watch for workpad state and then persist those changes
  const [workpad, canWrite] = (0, _reactRedux.useSelector)(state => [(0, _workpad.getWorkpad)(state), (0, _app.canUserWrite)(state)]);
  const previousWorkpad = (0, _usePrevious.default)(workpad);
  const workpadChanged = previousWorkpad && workpad !== previousWorkpad;
  (0, _react.useEffect)(() => {
    if (canWrite) {
      if (workpadChanged) {
        service.updateWorkpad(workpad.id, workpad).catch(err => {
          (0, _assets.notifyError)(err, notifyService.error);
        });
      }
    }
  }, [service, workpad, workpadChanged, canWrite, notifyService.error]);
};
exports.useWorkpadPersist = useWorkpadPersist;