/* wp:polyfill */
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
exports.useAugmentPatternsWithPermissions = useAugmentPatternsWithPermissions;
exports.usePatterns = void 0;
var _blocks = require("@wordpress/blocks");
var _data = require("@wordpress/data");
var _coreData = require("@wordpress/core-data");
var _element = require("@wordpress/element");
var _utils = require("./utils");
var _constants = require("../../utils/constants");
var _lockUnlock = require("../../lock-unlock");
var _searchItems = require("./search-items");
var _store = require("../../store");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const EMPTY_PATTERN_LIST = [];
const selectTemplateParts = (0, _data.createSelector)((select, categoryId, search = '') => {
  var _getEntityRecords;
  const {
    getEntityRecords,
    isResolving: isResolvingSelector
  } = select(_coreData.store);
  const query = {
    per_page: -1
  };
  const templateParts = (_getEntityRecords = getEntityRecords('postType', _constants.TEMPLATE_PART_POST_TYPE, query)) !== null && _getEntityRecords !== void 0 ? _getEntityRecords : EMPTY_PATTERN_LIST;

  // In the case where a custom template part area has been removed we need
  // the current list of areas to cross check against so orphaned template
  // parts can be treated as uncategorized.
  const knownAreas = select(_coreData.store).getEntityRecord('root', '__unstableBase')?.default_template_part_areas || [];
  const templatePartAreas = knownAreas.map(area => area.area);
  const templatePartHasCategory = (item, category) => {
    if (category !== _constants.TEMPLATE_PART_AREA_DEFAULT_CATEGORY) {
      return item.area === category;
    }
    return item.area === category || !templatePartAreas.includes(item.area);
  };
  const isResolving = isResolvingSelector('getEntityRecords', ['postType', _constants.TEMPLATE_PART_POST_TYPE, query]);
  const patterns = (0, _searchItems.searchItems)(templateParts, search, {
    categoryId,
    hasCategory: templatePartHasCategory
  });
  return {
    patterns,
    isResolving
  };
}, select => [select(_coreData.store).getEntityRecords('postType', _constants.TEMPLATE_PART_POST_TYPE, {
  per_page: -1
}), select(_coreData.store).isResolving('getEntityRecords', ['postType', _constants.TEMPLATE_PART_POST_TYPE, {
  per_page: -1
}]), select(_coreData.store).getEntityRecord('root', '__unstableBase')?.default_template_part_areas]);
const selectThemePatterns = (0, _data.createSelector)(select => {
  var _settings$__experimen;
  const {
    getSettings
  } = (0, _lockUnlock.unlock)(select(_store.store));
  const {
    isResolving: isResolvingSelector
  } = select(_coreData.store);
  const settings = getSettings();
  const blockPatterns = (_settings$__experimen = settings.__experimentalAdditionalBlockPatterns) !== null && _settings$__experimen !== void 0 ? _settings$__experimen : settings.__experimentalBlockPatterns;
  const restBlockPatterns = select(_coreData.store).getBlockPatterns();
  const patterns = [...(blockPatterns || []), ...(restBlockPatterns || [])].filter(pattern => !_constants.EXCLUDED_PATTERN_SOURCES.includes(pattern.source)).filter(_utils.filterOutDuplicatesByName).filter(pattern => pattern.inserter !== false).map(pattern => ({
    ...pattern,
    keywords: pattern.keywords || [],
    type: _constants.PATTERN_TYPES.theme,
    blocks: (0, _blocks.parse)(pattern.content, {
      __unstableSkipMigrationLogs: true
    })
  }));
  return {
    patterns,
    isResolving: isResolvingSelector('getBlockPatterns')
  };
}, select => [select(_coreData.store).getBlockPatterns(), select(_coreData.store).isResolving('getBlockPatterns'), (0, _lockUnlock.unlock)(select(_store.store)).getSettings()]);
const selectPatterns = (0, _data.createSelector)((select, categoryId, syncStatus, search = '') => {
  const {
    patterns: themePatterns,
    isResolving: isResolvingThemePatterns
  } = selectThemePatterns(select);
  const {
    patterns: userPatterns,
    isResolving: isResolvingUserPatterns,
    categories: userPatternCategories
  } = selectUserPatterns(select);
  let patterns = [...(themePatterns || []), ...(userPatterns || [])];
  if (syncStatus) {
    // User patterns can have their sync statuses checked directly
    // Non-user patterns are all unsynced for the time being.
    patterns = patterns.filter(pattern => {
      return pattern.type === _constants.PATTERN_TYPES.user ? (pattern.wp_pattern_sync_status || _constants.PATTERN_SYNC_TYPES.full) === syncStatus : syncStatus === _constants.PATTERN_SYNC_TYPES.unsynced;
    });
  }
  if (categoryId) {
    patterns = (0, _searchItems.searchItems)(patterns, search, {
      categoryId,
      hasCategory: (item, currentCategory) => {
        if (item.type === _constants.PATTERN_TYPES.user) {
          return item.wp_pattern_category?.some(catId => userPatternCategories.find(cat => cat.id === catId)?.slug === currentCategory);
        }
        return item.categories?.includes(currentCategory);
      }
    });
  } else {
    patterns = (0, _searchItems.searchItems)(patterns, search, {
      hasCategory: item => {
        if (item.type === _constants.PATTERN_TYPES.user) {
          return userPatternCategories?.length && (!item.wp_pattern_category?.length || !item.wp_pattern_category?.some(catId => userPatternCategories.find(cat => cat.id === catId)));
        }
        return !item.hasOwnProperty('categories');
      }
    });
  }
  return {
    patterns,
    isResolving: isResolvingThemePatterns || isResolvingUserPatterns
  };
}, select => [selectThemePatterns(select), selectUserPatterns(select)]);
const selectUserPatterns = (0, _data.createSelector)((select, syncStatus, search = '') => {
  const {
    getEntityRecords,
    isResolving: isResolvingSelector,
    getUserPatternCategories
  } = select(_coreData.store);
  const query = {
    per_page: -1
  };
  const patternPosts = getEntityRecords('postType', _constants.PATTERN_TYPES.user, query);
  const userPatternCategories = getUserPatternCategories();
  const categories = new Map();
  userPatternCategories.forEach(userCategory => categories.set(userCategory.id, userCategory));
  let patterns = patternPosts !== null && patternPosts !== void 0 ? patternPosts : EMPTY_PATTERN_LIST;
  const isResolving = isResolvingSelector('getEntityRecords', ['postType', _constants.PATTERN_TYPES.user, query]);
  if (syncStatus) {
    patterns = patterns.filter(pattern => pattern.wp_pattern_sync_status || _constants.PATTERN_SYNC_TYPES.full === syncStatus);
  }
  patterns = (0, _searchItems.searchItems)(patterns, search, {
    // We exit user pattern retrieval early if we aren't in the
    // catch-all category for user created patterns, so it has
    // to be in the category.
    hasCategory: () => true
  });
  return {
    patterns,
    isResolving,
    categories: userPatternCategories
  };
}, select => [select(_coreData.store).getEntityRecords('postType', _constants.PATTERN_TYPES.user, {
  per_page: -1
}), select(_coreData.store).isResolving('getEntityRecords', ['postType', _constants.PATTERN_TYPES.user, {
  per_page: -1
}]), select(_coreData.store).getUserPatternCategories()]);
function useAugmentPatternsWithPermissions(patterns) {
  const idsAndTypes = (0, _element.useMemo)(() => {
    var _patterns$filter$map;
    return (_patterns$filter$map = patterns?.filter(record => record.type !== _constants.PATTERN_TYPES.theme).map(record => [record.type, record.id])) !== null && _patterns$filter$map !== void 0 ? _patterns$filter$map : [];
  }, [patterns]);
  const permissions = (0, _data.useSelect)(select => {
    const {
      getEntityRecordPermissions
    } = (0, _lockUnlock.unlock)(select(_coreData.store));
    return idsAndTypes.reduce((acc, [type, id]) => {
      acc[id] = getEntityRecordPermissions('postType', type, id);
      return acc;
    }, {});
  }, [idsAndTypes]);
  return (0, _element.useMemo)(() => {
    var _patterns$map;
    return (_patterns$map = patterns?.map(record => {
      var _permissions$record$i;
      return {
        ...record,
        permissions: (_permissions$record$i = permissions?.[record.id]) !== null && _permissions$record$i !== void 0 ? _permissions$record$i : {}
      };
    })) !== null && _patterns$map !== void 0 ? _patterns$map : [];
  }, [patterns, permissions]);
}
const usePatterns = (postType, categoryId, {
  search = '',
  syncStatus
} = {}) => {
  return (0, _data.useSelect)(select => {
    if (postType === _constants.TEMPLATE_PART_POST_TYPE) {
      return selectTemplateParts(select, categoryId, search);
    } else if (postType === _constants.PATTERN_TYPES.user && !!categoryId) {
      const appliedCategory = categoryId === 'uncategorized' ? '' : categoryId;
      return selectPatterns(select, appliedCategory, syncStatus, search);
    } else if (postType === _constants.PATTERN_TYPES.user) {
      return selectUserPatterns(select, syncStatus, search);
    }
    return {
      patterns: EMPTY_PATTERN_LIST,
      isResolving: false
    };
  }, [categoryId, postType, search, syncStatus]);
};
exports.usePatterns = usePatterns;
var _default = exports.default = usePatterns;
//# sourceMappingURL=use-patterns.js.map