package com.bytesw.bytebot.etl.batch.factory.reader;

import com.bytesw.bytebot.etl.batch.beans.DynaBean;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.util.Map;

/**
 * Params:
 *  -jdbc-driver
 *  -username
 *  -password
 *  -jdbc-url
 *  -query
 */
@Component
@Log4j2
public class DataBaseItemReaderFactory implements ItemReaderFactory<DynaBean, RowMapper<DynaBean>> {


    @Override
    public ItemReader<DynaBean> createReader(RowMapper<DynaBean> mapper, Map<String, Object> params) {


        JdbcCursorItemReader<DynaBean> databaseReader;
        databaseReader = new ByteDataBaseItemReaderFactory<>();

        String jdbcDriver = params.containsKey("jdbc-driver") ? String.valueOf(params.get("jdbc-driver")): null;;
        Assert.isTrue(jdbcDriver != null, "jdbc-driver is required!");

        String username = params.containsKey("username") ? String.valueOf(params.get("username")): null;;
        Assert.isTrue(username != null, "username is required!");

        String password = params.containsKey("password") ? String.valueOf(params.get("password")): null;;
        Assert.isTrue(password != null, "password is required!");

        String jdbcURL = params.containsKey("jdbc-url") ? String.valueOf(params.get("jdbc-url")): null;;
        Assert.isTrue(jdbcURL != null, "jdbc-url is required!");

        String query = params.containsKey("query") ? String.valueOf(params.get("query")): null;;
        Assert.isTrue(query != null, "query is required!");

        DataSource dataSource = getBasicDataSource(jdbcDriver, username, password, jdbcURL);

        databaseReader.setDataSource(dataSource);
        databaseReader.setRowMapper(mapper);
        databaseReader.setSql(query);

        return databaseReader;
    }

    protected DataSource getBasicDataSource(String jdbcDriver, String username, String password, String jdbcURL) {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(jdbcDriver);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setUrl(jdbcURL);
        return dataSource;
    }

}
