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

import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.database.JdbcCursorItemReader;

@Log4j2
public class ByteDataBaseItemReaderFactory<T> extends JdbcCursorItemReader<T> implements StepExecutionListener {

    @Override
    public void beforeStep(StepExecution stepExecution) {

    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        closeDatabase();
        return stepExecution.getExitStatus();
    }

    private void closeDatabase() {
        if (this.getDataSource() instanceof BasicDataSource) {
            BasicDataSource dataSource = (BasicDataSource) this.getDataSource();
            if (!dataSource.isClosed()) {
                try {
                    dataSource.close();
                } catch (Exception e) {
                    log.debug(e.getMessage());
                }
            }
        }
    }

}
