/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2015, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.as.clustering.infinispan.subsystem;

import static org.jboss.as.clustering.infinispan.subsystem.CacheResourceDefinition.Attribute.STATISTICS_ENABLED;
import static org.jboss.as.clustering.infinispan.subsystem.CacheResourceDefinition.Capability.CONFIGURATION;

import java.util.List;
import java.util.function.Consumer;

import org.infinispan.commons.CacheException;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.cache.ExpirationConfiguration;
import org.infinispan.configuration.cache.GroupsConfigurationBuilder;
import org.infinispan.configuration.cache.LockingConfiguration;
import org.infinispan.configuration.cache.MemoryConfiguration;
import org.infinispan.configuration.cache.PersistenceConfiguration;
import org.infinispan.configuration.cache.StorageType;
import org.infinispan.configuration.cache.TransactionConfiguration;
import org.infinispan.distribution.group.Grouper;
import org.infinispan.transaction.tm.EmbeddedTransactionManager;
import org.jboss.as.clustering.controller.CapabilityServiceNameProvider;
import org.jboss.as.clustering.controller.ResourceServiceConfigurator;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.dmr.ModelNode;
import org.jboss.modules.Module;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceTarget;
import org.wildfly.clustering.infinispan.service.ConfigurationServiceConfigurator;
import org.wildfly.clustering.service.CompositeDependency;
import org.wildfly.clustering.service.Dependency;
import org.wildfly.clustering.service.ServiceConfigurator;
import org.wildfly.clustering.service.ServiceSupplierDependency;
import org.wildfly.clustering.service.SupplierDependency;

/**
 * Builds a cache configuration from its components.
 * @author Paul Ferraro
 */
public class CacheConfigurationServiceConfigurator extends CapabilityServiceNameProvider implements ResourceServiceConfigurator, Consumer<ConfigurationBuilder>, Dependency {

    private final ConfigurationServiceConfigurator configurator;
    private final SupplierDependency<MemoryConfiguration> memory;
    private final SupplierDependency<ExpirationConfiguration> expiration;
    private final SupplierDependency<LockingConfiguration> locking;
    private final SupplierDependency<PersistenceConfiguration> persistence;
    private final SupplierDependency<TransactionConfiguration> transaction;
    private final SupplierDependency<List<Module>> modules;

    private volatile boolean statisticsEnabled;

    CacheConfigurationServiceConfigurator(PathAddress address) {
        super(CONFIGURATION, address);
        this.memory = new ServiceSupplierDependency<>(CacheComponent.MEMORY.getServiceName(address));
        this.expiration = new ServiceSupplierDependency<>(CacheComponent.EXPIRATION.getServiceName(address));
        this.locking = new ServiceSupplierDependency<>(CacheComponent.LOCKING.getServiceName(address));
        this.persistence = new ServiceSupplierDependency<>(CacheComponent.PERSISTENCE.getServiceName(address));
        this.transaction = new ServiceSupplierDependency<>(CacheComponent.TRANSACTION.getServiceName(address));
        this.modules = new ServiceSupplierDependency<>(CacheComponent.MODULES.getServiceName(address));

        String containerName = address.getParent().getLastElement().getValue();
        String cacheName = address.getLastElement().getValue();
        this.configurator = new ConfigurationServiceConfigurator(this.getServiceName(), containerName, cacheName, this.andThen(builder -> {
            if (builder.memory().storage() == StorageType.HEAP) {
                GroupsConfigurationBuilder groupsBuilder = builder.clustering().hash().groups().enabled();
                for (Module module : this.modules.get()) {
                    for (Grouper<?> grouper : module.loadService(Grouper.class)) {
                        groupsBuilder.addGrouper(grouper);
                    }
                }
            }
        })).require(this);
    }

    @Override
    public ServiceBuilder<?> build(ServiceTarget target) {
        return this.configurator.build(target);
    }

    @Override
    public <T> ServiceBuilder<T> register(ServiceBuilder<T> builder) {
        return new CompositeDependency(this.memory, this.expiration, this.locking, this.persistence, this.transaction, this.modules).register(builder);
    }

    @Override
    public ServiceConfigurator configure(OperationContext context, ModelNode model) throws OperationFailedException {
        this.statisticsEnabled = STATISTICS_ENABLED.resolveModelAttribute(context, model).asBoolean();

        this.configurator.configure(context);
        return this;
    }

    @Override
    public void accept(ConfigurationBuilder builder) {
        TransactionConfiguration tx = this.transaction.get();

        builder.memory().read(this.memory.get());
        builder.expiration().read(this.expiration.get());
        builder.locking().read(this.locking.get());
        builder.persistence().read(this.persistence.get());
        builder.transaction().read(tx);
        builder.statistics().enabled(this.statisticsEnabled);

        // See WFLY-14356
        if (this.memory.get().storage().canStoreReferences()) {
            builder.encoding().mediaType(MediaType.APPLICATION_OBJECT_TYPE);
        }
        try {
            // Configure invocation batching based on transaction configuration
            builder.invocationBatching().enable(tx.transactionMode().isTransactional() && (tx.transactionManagerLookup().getTransactionManager() == EmbeddedTransactionManager.getInstance()));
        } catch (Exception e) {
            throw new CacheException(e);
        }
    }

    MemoryConfiguration memory() {
        return this.memory.get();
    }

    PersistenceConfiguration persistence() {
        return this.persistence.get();
    }

    TransactionConfiguration transaction() {
        return this.transaction.get();
    }
}

@@ -1299,31 +1299,8 @@
 N;%0A%0A
-import java.util.List;%0A
 impo
@@ -1331,16 +1331,16 @@
 nsumer;%0A
+
 %0Aimport 
@@ -1569,78 +1569,8 @@
 on;%0A
-import org.infinispan.configuration.cache.GroupsConfigurationBuilder;%0A
 impo
@@ -1764,63 +1764,8 @@
 on;%0A
-import org.infinispan.configuration.cache.StorageType;%0A
 impo
@@ -1832,58 +1832,8 @@
 on;%0A
-import org.infinispan.distribution.group.Grouper;%0A
 impo
@@ -2223,41 +2223,8 @@
 de;%0A
-import org.jboss.modules.Module;%0A
 impo
@@ -3371,68 +3371,8 @@
 ion;
-%0A    private final SupplierDependency%3CList%3CModule%3E%3E modules;
 %0A%0A  
@@ -4065,112 +4065,8 @@
 s));
-%0A        this.modules = new ServiceSupplierDependency%3C%3E(CacheComponent.MODULES.getServiceName(address));
 %0A%0A  
@@ -4329,468 +4329,8 @@
 this
-.andThen(builder -%3E %7B%0A            if (builder.memory().storage() == StorageType.HEAP) %7B%0A                GroupsConfigurationBuilder groupsBuilder = builder.clustering().hash().groups().enabled();%0A                for (Module module : this.modules.get()) %7B%0A                    for (Grouper%3C?%3E grouper : module.loadService(Grouper.class)) %7B%0A                        groupsBuilder.addGrouper(grouper);%0A                    %7D%0A                %7D%0A            %7D%0A        %7D)
 ).re
@@ -4554,32 +4554,32 @@
 r%3CT%3E builder) %7B%0A
+
         return n
@@ -4683,22 +4683,8 @@
 tion
-, this.modules
 ).re

Drop obsolete grouper configuration logic.