/**
 * Copyright 2015-2016 Red Hat, Inc, and individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.wildfly.swarm.keycloak.server.runtime;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import javax.enterprise.inject.Any;
import javax.inject.Inject;
import javax.inject.Singleton;

import org.wildfly.swarm.bootstrap.util.TempFileManager;
import org.wildfly.swarm.config.infinispan.CacheContainer;
import org.wildfly.swarm.config.infinispan.cache_container.TransactionComponent;
import org.wildfly.swarm.datasources.DatasourcesFraction;
import org.wildfly.swarm.infinispan.InfinispanFraction;
import org.wildfly.swarm.spi.api.Customizer;
import org.wildfly.swarm.spi.runtime.annotations.Post;

/**
 * @author Bob McWhirter
 */
@Post
@Singleton
public class KeycloakServerCustomizer implements Customizer {

    @Inject @Any
    private InfinispanFraction infinispan;

    @Inject @Any
    private DatasourcesFraction datasources;


    @Override
    public void customize() {

        if (System.getProperty("jboss.server.config.dir") == null) {
            try {
                //Path dir = Files.createTempDirectory("swarm-keycloak-config");
                File dir = TempFileManager.INSTANCE.newTempDirectory("swarm-keycloak-config", ".d");
                System.setProperty("jboss.server.config.dir", dir.getAbsolutePath());
                Files.copy(getClass().getClassLoader().getResourceAsStream("keycloak-server.json"),
                        dir.toPath().resolve("keycloak-server.json"),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        CacheContainer cache = infinispan.subresources().cacheContainer("keycloak");
        if (cache == null) {
            infinispan.cacheContainer("keycloak", (c) -> c.jndiName("infinispan/Keycloak")
                    .localCache("realms")
                    .localCache("users")
                    .localCache("sessions")
                    .localCache("offlineSessions")
                    .localCache("loginFailures")
                    .localCache("work")
                    .localCache("realmVersions", (ca) -> ca.transactionComponent(new TransactionComponent()
                            .mode(TransactionComponent.Mode.BATCH)
                            .locking(TransactionComponent.Locking.PESSIMISTIC)))
            );
        }

        if (datasources.subresources().dataSource("KeycloakDS") == null) {
            if (datasources.subresources().jdbcDriver("h2") == null) {
                datasources.jdbcDriver("h2", (driver) -> {
                    driver.driverModuleName("com.h2database.h2");
                    driver.moduleSlot("main");
                    driver.xaDatasourceClass("org.h2.jdbcx.JdbcDataSource");
                });
            }

            datasources.dataSource("KeycloakDS", (ds) -> {
                ds.jndiName("java:jboss/datasources/KeycloakDS");
                ds.useJavaContext(true);
                ds.connectionUrl("jdbc:h2:${wildfly.swarm.keycloak.server.db:./keycloak};AUTO_SERVER=TRUE");
                ds.driverName("h2");
                ds.userName("sa");
                ds.password("sa");
            });
        }

    }
}

@@ -1000,24 +1000,102 @@
 eContainer;%0A
+import org.wildfly.swarm.config.infinispan.cache_container.EvictionComponent;%0A
 import org.w
@@ -1155,32 +1155,32 @@
 ctionComponent;%0A
-
 import org.wildf
@@ -1494,32 +1494,36 @@
 r %7B%0A%0A    @Inject
+%0A   
  @Any%0A    privat
@@ -1567,16 +1567,20 @@
  @Inject
+%0A   
  @Any%0A  
@@ -2148,16 +2148,19 @@
         
+   
 dir.toPa
@@ -2189,32 +2189,35 @@
 -server.json%22),%0A
+   
                 
@@ -2942,16 +2942,77 @@
 onent()%0A
+                                                             
         
@@ -3102,57 +3102,463 @@
     
-.locking(TransactionComponent.Locking.PESSIMISTIC
+                                                             .locking(TransactionComponent.Locking.PESSIMISTIC)))%0A                    .localCache(%22authorization%22, (ca) -%3E ca.evictionComponent(new EvictionComponent()%0A                                                                                      .strategy(EvictionComponent.Strategy.LRU)%0A                                                                                      .maxEntries(new Long(100)
 )))%0A

add authorization cache