/*
 * Copyright 2020 Red Hat, Inc. and/or its affiliates.
 *
 * 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.kie.kogito.persistence.infinispan.cache;

import java.io.InputStream;
import java.util.Scanner;

import org.infinispan.commons.configuration.XMLStringConfiguration;

/**
 * Default process event cache configuration
 * 
 */
public class KogitoCacheDefaultConfiguration extends XMLStringConfiguration {

    private static final String CACHE_CONFIG_PATH = "META-INF/kogito-cache-default.xml";
    private static final String CACHE_NAME_PLACEHOLDER = "${cache_name}";

    public KogitoCacheDefaultConfiguration(final String cacheName) {
        super(defaultCacheTemplate(cacheName));
    }

    private static final String defaultCacheTemplate(final String cacheName) {
        final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(CACHE_CONFIG_PATH);
        if (is == null) {
            throw new IllegalArgumentException(String.format("Cache configuration file %s not found", CACHE_CONFIG_PATH));
        }

        try (Scanner s = new Scanner(is)) {
            s.useDelimiter("\\A");
            final String xmlCacheConfig = s.hasNext() ? s.next() : "";
            return xmlCacheConfig.replace(CACHE_NAME_PLACEHOLDER, cacheName);
        }
    }

}
