"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useAvailablePackages = void 0;
var _react = _interopRequireWildcard(require("react"));
var _lodash = require("lodash");
var _hooks = require("../../../../../hooks");
var _use_merge_epr_with_replacements = require("../../../../../hooks/use_merge_epr_with_replacements");
var _ = require("..");
var _services = require("../../../../../services");
var _services2 = require("../../../../../../../../common/services");
var _category_facets = require("../category_facets");
var _util = require("../util");
var _use_build_integrations_url = require("./use_build_integrations_url");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * 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.
 */

function getAllCategoriesFromIntegrations(pkg) {
  var _pkg$policy_templates;
  if (!(0, _services.doesPackageHaveIntegrations)(pkg)) {
    return pkg.categories;
  }
  const allCategories = (_pkg$policy_templates = pkg.policy_templates) === null || _pkg$policy_templates === void 0 ? void 0 : _pkg$policy_templates.reduce((accumulator, policyTemplate) => {
    if ((0, _services2.isInputOnlyPolicyTemplate)(policyTemplate)) {
      // input only policy templates do not have categories
      return accumulator;
    }
    return [...accumulator, ...(policyTemplate.categories || [])];
  }, pkg.categories || []);
  return (0, _lodash.uniq)(allCategories);
}

// Packages can export multiple integrations, aka `policy_templates`
// In the case where packages ship >1 `policy_templates`, we flatten out the
// list of packages by bringing all integrations to top-level so that
// each integration is displayed as its own tile
const packageListToIntegrationsList = packages => {
  return packages.reduce((acc, pkg) => {
    const {
      policy_templates: policyTemplates = [],
      categories: topCategories = [],
      ...restOfPackage
    } = pkg;
    const topPackage = {
      ...restOfPackage,
      categories: getAllCategoriesFromIntegrations(pkg)
    };
    return [...acc, topPackage, ...((0, _services.doesPackageHaveIntegrations)(pkg) ? policyTemplates.map(policyTemplate => {
      const {
        name,
        title,
        description,
        icons
      } = policyTemplate;
      const categories = (0, _services2.isIntegrationPolicyTemplate)(policyTemplate) && policyTemplate.categories ? policyTemplate.categories : [];
      const allCategories = [...topCategories, ...categories];
      return {
        ...restOfPackage,
        id: `${restOfPackage.id}-${name}`,
        integration: name,
        title,
        description,
        icons: icons || restOfPackage.icons,
        categories: (0, _lodash.uniq)(allCategories)
      };
    }) : [])];
  }, []);
};
const useAvailablePackages = () => {
  const [preference, setPreference] = (0, _react.useState)('recommended');
  const [prereleaseIntegrationsEnabled, setPrereleaseIntegrationsEnabled] = _react.default.useState(undefined);
  const {
    showIntegrationsSubcategories
  } = _services.ExperimentalFeaturesService.get();
  const {
    initialSelectedCategory,
    initialSubcategory,
    setUrlandPushHistory,
    setUrlandReplaceHistory,
    getHref,
    getAbsolutePath,
    searchParam,
    addBasePath
  } = (0, _use_build_integrations_url.useBuildIntegrationsUrl)();
  const [selectedCategory, setCategory] = (0, _react.useState)(initialSelectedCategory);
  const [selectedSubCategory, setSelectedSubCategory] = (0, _react.useState)(initialSubcategory);
  const [searchTerm, setSearchTerm] = (0, _react.useState)(searchParam || '');
  const {
    data: eprPackages,
    isLoading: isLoadingAllPackages,
    error: eprPackageLoadingError
  } = (0, _hooks.useGetPackagesQuery)({
    prerelease: prereleaseIntegrationsEnabled
  });

  // Remove Kubernetes package granularity
  if (eprPackages !== null && eprPackages !== void 0 && eprPackages.items) {
    eprPackages.items.forEach(function (element) {
      if (element.id === 'kubernetes') {
        element.policy_templates = [];
      }
    });
  }
  const eprIntegrationList = (0, _react.useMemo)(() => packageListToIntegrationsList((eprPackages === null || eprPackages === void 0 ? void 0 : eprPackages.items) || []), [eprPackages]);
  const {
    data: replacementCustomIntegrations,
    isInitialLoading: isLoadingReplacmentCustomIntegrations
  } = (0, _hooks.useGetReplacementCustomIntegrationsQuery)();
  const {
    isInitialLoading: isLoadingAppendCustomIntegrations,
    data: appendCustomIntegrations
  } = (0, _hooks.useGetAppendCustomIntegrationsQuery)();
  const mergedEprPackages = (0, _use_merge_epr_with_replacements.useMergeEprPackagesWithReplacements)(preference === 'beats' ? [] : eprIntegrationList, preference === 'agent' ? [] : replacementCustomIntegrations || []);
  const cards = (0, _react.useMemo)(() => {
    const eprAndCustomPackages = [...mergedEprPackages, ...(appendCustomIntegrations || [])];
    return eprAndCustomPackages.map(item => {
      return (0, _.mapToCard)({
        getAbsolutePath,
        getHref,
        item,
        addBasePath
      });
    }).sort((a, b) => a.title.localeCompare(b.title));
  }, [addBasePath, appendCustomIntegrations, getAbsolutePath, getHref, mergedEprPackages]);

  // Packages to show
  // Filters out based on selected category and subcategory (if any)
  const filteredCards = (0, _react.useMemo)(() => cards.filter(c => {
    if (selectedCategory === '') {
      return true;
    }
    if (!selectedSubCategory) return c.categories.includes(selectedCategory);
    return c.categories.includes(selectedSubCategory);
  }), [cards, selectedCategory, selectedSubCategory]);
  const {
    data: eprCategoriesRes,
    isLoading: isLoadingCategories,
    error: eprCategoryLoadingError
  } = (0, _hooks.useGetCategoriesQuery)({
    prerelease: prereleaseIntegrationsEnabled
  });
  const eprCategories = (0, _react.useMemo)(() => (eprCategoriesRes === null || eprCategoriesRes === void 0 ? void 0 : eprCategoriesRes.items) || [], [eprCategoriesRes]);
  const allCategories = (0, _react.useMemo)(() => {
    const eprAndCustomCategories = isLoadingCategories ? [] : (0, _util.mergeCategoriesAndCount)(eprCategories ? eprCategories : [], cards);
    return [{
      ..._category_facets.ALL_CATEGORY,
      count: cards.length
    }, ...(eprAndCustomCategories ? eprAndCustomCategories : [])];
  }, [cards, eprCategories, isLoadingCategories]);

  // Filter out subcategories
  const mainCategories = (0, _react.useMemo)(() => {
    return showIntegrationsSubcategories ? allCategories.filter(category => category.parent_id === undefined) : allCategories;
  }, [allCategories, showIntegrationsSubcategories]);
  const availableSubCategories = (0, _react.useMemo)(() => {
    return showIntegrationsSubcategories ? allCategories === null || allCategories === void 0 ? void 0 : allCategories.filter(c => c.parent_id === selectedCategory) : [];
  }, [allCategories, selectedCategory, showIntegrationsSubcategories]);
  return {
    initialSelectedCategory,
    selectedCategory,
    setCategory,
    allCategories,
    mainCategories,
    availableSubCategories,
    selectedSubCategory,
    setSelectedSubCategory,
    searchTerm,
    setSearchTerm,
    setUrlandPushHistory,
    setUrlandReplaceHistory,
    preference,
    setPreference,
    isLoading: isLoadingReplacmentCustomIntegrations || isLoadingAppendCustomIntegrations || isLoadingCategories || isLoadingAllPackages,
    isLoadingCategories,
    isLoadingAllPackages,
    isLoadingAppendCustomIntegrations,
    eprPackageLoadingError,
    eprCategoryLoadingError,
    filteredCards,
    setPrereleaseIntegrationsEnabled
  };
};
exports.useAvailablePackages = useAvailablePackages;