package no.valg.valgnatt.database;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import db.migration.V20150000_002__Baseline_Load;

@Component("flywayLoader")
public class FlywayLoader {

    @Resource
    private Configuration configuration;

    @Resource
    private DataSource dataSource;

    @PostConstruct
    public void initialize() throws IOException {
        if (new PathMatchingResourcePatternResolver().getResources("file:" + Konstanter.AUTOOPPSETT_INITIALDATAKATALOG + "/*.csv").length > 0) {
            configuration.setInitialdata(Konstanter.AUTOOPPSETT_INITIALDATA);
        }
        // Hack until if/when https://github.com/flyway/flyway/issues/805 is implemented in Flyway
        V20150000_002__Baseline_Load.setInitialdata(configuration.getInitialdata());

        Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setSchemas(configuration.getFlywaySchemas());
        flyway.migrate();
    }

}
