/*
 * 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.sdm.db.utils;

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.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;

import com.scytl.products.ov.sdm.infrastructure.DatabaseManager;
import com.scytl.products.ov.sdm.infrastructure.DatabaseManagerFactoryImpl;

@Configuration
@ComponentScan({
        "com.scytl.products.ov.sdm.infrastructure.administrationauthority",
        "com.scytl.products.ov.sdm.infrastructure.ballot",
        "com.scytl.products.ov.sdm.infrastructure.ballotbox",
        "com.scytl.products.ov.sdm.infrastructure.ballotboxcounting",
        "com.scytl.products.ov.sdm.infrastructure.ballotboxtallying",
        "com.scytl.products.ov.sdm.infrastructure.ballottext",
        "com.scytl.products.ov.sdm.infrastructure.electionevent",
        "com.scytl.products.ov.sdm.infrastructure.electoralauthority",
        "com.scytl.products.ov.sdm.infrastructure.verificationcardset",
        "com.scytl.products.ov.sdm.infrastructure.votingcardset" })
@PropertySource("classpath:application.properties")
public class SpringConfig {

    @Autowired
    Environment environment;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean(initMethod = "createDatabase")
    DatabaseManager manager() {
        String url = environment.getProperty("database.args.path");
        if (url == null) {
            url = environment.getProperty("database.path");
        }
        if (url == null) {
            throw new IllegalStateException("Data base URL is not set.");
        }
        return new DatabaseManagerFactoryImpl().newDatabaseManager(url);
    }
}
