"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SecurityLogic = void 0;
var _kea = require("kea");
var _lodash = require("lodash");
var _flash_messages = require("../../../shared/flash_messages");
var _http = require("../../../shared/http");
var _app_logic = require("../../app_logic");
var _constants = require("../../constants");
/*
 * 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 route = '/internal/workplace_search/org/security/source_restrictions';
const SecurityLogic = (0, _kea.kea)({
  path: ['enterprise_search', 'workplace_search', 'security_logic'],
  actions: {
    setServerProps: serverProps => serverProps,
    setSourceRestrictionsUpdated: serverProps => serverProps,
    initializeSourceRestrictions: () => true,
    saveSourceRestrictions: () => null,
    updatePrivateSourcesEnabled: isEnabled => ({
      isEnabled
    }),
    updateRemoteEnabled: isEnabled => ({
      isEnabled
    }),
    updateRemoteSource: (sourceId, isEnabled) => ({
      sourceId,
      isEnabled
    }),
    updateStandardEnabled: isEnabled => ({
      isEnabled
    }),
    updateStandardSource: (sourceId, isEnabled) => ({
      sourceId,
      isEnabled
    }),
    resetState: () => null
  },
  reducers: {
    dataLoading: [true, {
      setServerProps: () => false
    }],
    cachedServerState: [{}, {
      setServerProps: (_, serverProps) => (0, _lodash.cloneDeep)(serverProps),
      setSourceRestrictionsUpdated: (_, serverProps) => (0, _lodash.cloneDeep)(serverProps)
    }],
    isEnabled: [false, {
      setServerProps: (_, {
        isEnabled
      }) => isEnabled,
      setSourceRestrictionsUpdated: (_, {
        isEnabled
      }) => isEnabled,
      updatePrivateSourcesEnabled: (_, {
        isEnabled
      }) => isEnabled
    }],
    remote: [{}, {
      setServerProps: (_, {
        remote
      }) => remote,
      setSourceRestrictionsUpdated: (_, {
        remote
      }) => remote,
      updateRemoteEnabled: (state, {
        isEnabled
      }) => ({
        ...state,
        isEnabled
      }),
      updateRemoteSource: (state, {
        sourceId,
        isEnabled
      }) => updateSourceEnabled(state, sourceId, isEnabled)
    }],
    standard: [{}, {
      setServerProps: (_, {
        standard
      }) => standard,
      setSourceRestrictionsUpdated: (_, {
        standard
      }) => standard,
      updateStandardEnabled: (state, {
        isEnabled
      }) => ({
        ...state,
        isEnabled
      }),
      updateStandardSource: (state, {
        sourceId,
        isEnabled
      }) => updateSourceEnabled(state, sourceId, isEnabled)
    }]
  },
  selectors: ({
    selectors
  }) => ({
    unsavedChanges: [() => [selectors.cachedServerState, selectors.isEnabled, selectors.remote, selectors.standard], (cached, isEnabled, remote, standard) => cached.isEnabled !== isEnabled || !(0, _lodash.isEqual)(cached.remote, remote) || !(0, _lodash.isEqual)(cached.standard, standard)]
  }),
  listeners: ({
    actions,
    values
  }) => ({
    initializeSourceRestrictions: async () => {
      const {
        http
      } = _http.HttpLogic.values;
      try {
        const response = await http.get(route);
        actions.setServerProps(response);
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    saveSourceRestrictions: async () => {
      const {
        isEnabled,
        remote,
        standard
      } = values;
      const serverData = {
        isEnabled,
        remote,
        standard
      };
      const body = JSON.stringify(serverData);
      const {
        http
      } = _http.HttpLogic.values;
      try {
        const response = await http.patch(route, {
          body
        });
        actions.setSourceRestrictionsUpdated(response);
        (0, _flash_messages.flashSuccessToast)(_constants.SOURCE_RESTRICTIONS_SUCCESS_MESSAGE);
        _app_logic.AppLogic.actions.setSourceRestriction(isEnabled);
      } catch (e) {
        (0, _flash_messages.flashAPIErrors)(e);
      }
    },
    resetState: () => {
      actions.setServerProps((0, _lodash.cloneDeep)(values.cachedServerState));
      (0, _flash_messages.clearFlashMessages)();
    }
  })
});
exports.SecurityLogic = SecurityLogic;
const updateSourceEnabled = (section, id, isEnabled) => {
  const updatedSection = {
    ...section
  };
  const sources = updatedSection.contentSources;
  const sourceIndex = sources.findIndex(source => source.id === id);
  updatedSection.contentSources[sourceIndex] = {
    ...sources[sourceIndex],
    isEnabled
  };
  return updatedSection;
};