package cc.smtweb.framework.core.db.jdbc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * JDBC事务处理类，可以在try中使用自动结束事务
 *
 * @author xkliu
 */
public class JdbcTrans implements AutoCloseable {

    private Logger logger = LoggerFactory.getLogger("trans");
    protected long time = System.currentTimeMillis();
    protected String info = Thread.currentThread().getStackTrace()[6].getFileName() + "::::" + Thread.currentThread().getStackTrace()[6].getLineNumber();
    private AtomicInteger count = new AtomicInteger(1);

    public int getCount() {
        return count.get();
    }

    public void inc() {
        count.incrementAndGet();
    }

    public boolean canCommit() {
        return count.decrementAndGet() == 0;
    }

    public void doEnd(String ei) {
        long t = System.currentTimeMillis() - time;
        if (t > 10000L) {
            logger.info(info + "::::::" + t + "::::::" + ei);
        }
    }

    private DataSourceTransactionManager transactionManager;
    private TransactionStatus status;

    /**
     * 构造事务执行
     *
     * @param transactionManager spring事务管理对象
     */
    public JdbcTrans(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
        // 事务定义类
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // 返回事务对象
        this.status = transactionManager.getTransaction(def);
    }

    /**
     * 回滚事务
     */
    public void rollback() {
        if (status != null) {
            transactionManager.rollback(status);
            status = null;
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        if (status != null) {
            transactionManager.commit(status);
            status = null;
        }
    }

    /**
     * 实现自动关闭，回滚方式结束事务
     */
    @Override
    public void close() {
        this.rollback();
    }
}
