package ru.yandex.webmaster3.storage.util.sql;

import java.util.ArrayList;
import java.util.List;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author avhaliullin
 */
public class JdbcBuilder {
    public LogicalDB create(LogicalDataSource dataSource) {
        WriteJdbcTemplate mainTemplate = new WriteJdbcTemplate(dataSource.getMasterSource(), dataSource.getDbIdentity() + " master url=" + dataSource.getMasterSource().getUrl());

        TransactionTemplate transactionTemplate = new TransactionTemplate(new DataSourceTransactionManager(dataSource.getMasterSource()));

        List<IReadJdbcTemplate> slaves = new ArrayList<>();
        int index = 0;
        for (DataSource slaveSource : dataSource.getSlaveSources()) {
            slaves.add(new ReadJdbcTemplate(slaveSource, dataSource.getDbIdentity() + " slave " + (index++) + " url=" + slaveSource.getUrl()));
        }
        return new LogicalDB(dataSource.getDbIdentity(), transactionTemplate, mainTemplate, slaves);
    }
}
