class CreateDefinedIndexesFunction implements InternalFunction<Set<RegionConfig.Index>> {

  @Override
  @SuppressWarnings("deprecation")
  public void execute(FunctionContext<Set<RegionConfig.Index>> context) {
    Cache cache = context.getCache();
    QueryService queryService = cache.getQueryService();
    ResultSender<CliFunctionResult> sender = context.getResultSender();
    String memberId = cache.getDistributedSystem().getDistributedMember().getId();
    Set<RegionConfig.Index> indexDefinitions = context.getArguments();

    try {
      for (RegionConfig.Index indexDefinition : indexDefinitions) {
        String indexName = indexDefinition.getName();
        String regionPath = indexDefinition.getFromClause();
        String indexedExpression = indexDefinition.getExpression();
        org.apache.geode.cache.query.IndexType indexType =
            org.apache.geode.cache.query.IndexType.valueOfSynonym(indexDefinition.getType());

        if (indexType == org.apache.geode.cache.query.IndexType.PRIMARY_KEY) {
          queryService.defineKeyIndex(indexName, indexedExpression, regionPath);
        } else if (indexType == org.apache.geode.cache.query.IndexType.HASH) {
          queryService.defineHashIndex(indexName, indexedExpression, regionPath);
        } else {
          queryService.defineIndex(indexName, indexedExpression, regionPath);
        }
      }

      List<Index> indexes = queryService.createDefinedIndexes();

      if (!indexes.isEmpty()) {
        for (Index index : indexes) {
          sender.sendResult(
              new CliFunctionResult(memberId, true, "Created index " + index.getName()));
        }
      } else {
        sender.sendResult(
            new CliFunctionResult(memberId, true, CliStrings.DEFINE_INDEX__FAILURE__MSG));
      }

    } catch (MultiIndexCreationException multiIndexCreationException) {
      // Some indexes may have been created, so let's get those
      List<String> failedIndexes =
          new ArrayList<>(multiIndexCreationException.getFailedIndexNames());
      List<String> createdIndexes =
          indexDefinitions.stream().filter(i -> !failedIndexes.contains(i.getName()))
              .map(RegionConfig.Index::getName).collect(Collectors.toList());

      for (String index : createdIndexes) {
        sender.sendResult(new CliFunctionResult(memberId, true, "Created index " + index));
      }

      for (Map.Entry<String, Exception> ex : multiIndexCreationException.getExceptionsMap()
          .entrySet()) {
        sender.sendResult(new CliFunctionResult(memberId, false, String
            .format("Failed to create index %s: %s", ex.getKey(), ex.getValue().getMessage())));
      }
    } catch (Exception ex) {
      sender.sendResult(new CliFunctionResult(memberId, false, ex.getMessage()));
    } finally {
      queryService.clearDefinedIndexes();
    }

    sender.lastResult(null);
  }

}