/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.config.tenant;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.scytl.cryptolib.api.asymmetric.AsymmetricServiceAPI;
import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.api.primitives.PrimitivesServiceAPI;
import com.scytl.cryptolib.api.services.ServiceFactory;
import com.scytl.cryptolib.asymmetric.service.AsymmetricServiceFactoryHelper;
import com.scytl.cryptolib.primitives.service.PrimitivesServiceFactoryHelper;

@Configuration
@ComponentScan(basePackages = {"com.scytl.products.ov.config.tenant" })
@PropertySource("classpath:springConfig.properties")
public class SpringConfig {

    @Autowired
    Environment env;

    @Bean
    public GenericObjectPoolConfig genericObjectPoolConfig() {

        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxTotal(Integer.valueOf(env.getProperty("services.cryptolib.pool.size")));
        genericObjectPoolConfig.setMaxIdle(Integer.valueOf(env.getProperty("services.cryptolib.timeout")));

        return genericObjectPoolConfig;
    }

    @Bean
    public ServiceFactory<AsymmetricServiceAPI> asymmetricServiceAPIServiceFactory(
            final GenericObjectPoolConfig genericObjectPoolConfig) {
        return AsymmetricServiceFactoryHelper.getFactoryOfThreadSafeServices(genericObjectPoolConfig);
    }

    @Bean
    public ServiceFactory<PrimitivesServiceAPI> primitivesServiceAPIServiceFactory(
            final GenericObjectPoolConfig genericObjectPoolConfig) {
        return PrimitivesServiceFactoryHelper.getFactoryOfThreadSafeServices(genericObjectPoolConfig);
    }

    @Bean
    public AsymmetricServiceAPI asymmetricServiceAPI(
            final ServiceFactory<AsymmetricServiceAPI> asymmetricServiceAPIServiceFactory)
            throws GeneralCryptoLibException {
        return asymmetricServiceAPIServiceFactory.create();
    }

    @Bean
    public PrimitivesServiceAPI primitivesServiceAPI(
            final ServiceFactory<PrimitivesServiceAPI> primitivesServiceAPIServiceFactory)
            throws GeneralCryptoLibException {
        return primitivesServiceAPIServiceFactory.create();
    }
}
