package com.atlassian.bitbucket.transaction;

import com.atlassian.activeobjects.spi.TransactionSynchronisationManager;
import com.atlassian.sal.api.transaction.TransactionCallback;
import com.google.common.collect.Lists;
import org.slf4j.Logger;

import java.util.List;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * A simple implementation of {@link TransactionSynchronisationManager} for testing purposes. It must be passed to
 * a {@link SimpleSalTransactionTemplate}'s
 * {@link SimpleSalTransactionTemplate#SimpleSalTransactionTemplate(SimpleSalTransactionSynchronisationManager) ctor}
 * for correct behaviour around transaction boundaries (for rollback and commit actions to be executed).
 * <p>
 * {@link #runOnSuccessfulCommit(Runnable) Commit actions} will be executed when the top-most call to
 * {@link SimpleSalTransactionTemplate#execute(TransactionCallback)} returns without error and no nested call
 * have thrown an exception. Nested calls do not trigger commit action execution.
 * <p>
 * {@link #runOnRollBack(Runnable) Rollback actions} will be executed when the top-most call to
 * {@link SimpleSalTransactionTemplate#execute(TransactionCallback)} throws an exception or returns when a nested
 * call has thrown an exception (simulating mark-as-rollback semantics)
 * <p>
 * Rollback and commit actions are stored per-thread.
 */
public class SimpleSalTransactionSynchronisationManager implements TransactionSynchronisationManager {
    private static final Logger log = getLogger(SimpleSalTransactionSynchronisationManager.class);
    private static final ThreadLocal<TxInfo> tlsTxInfo = ThreadLocal.withInitial(TxInfo::new);

    private SimpleSalTransactionTemplate template;

    public void onRollback() {
        for (Runnable rollbackAction : tlsTxInfo.get().rollbackActions) {
            try {
                rollbackAction.run();
            } catch (Exception e) {
                log.error("Exception during rollback action", e);
            }
        }
    }

    public void onCommit() {
        for (Runnable commitAction : tlsTxInfo.get().commitActions) {
            try {
                commitAction.run();
            } catch (Exception e) {
                log.error("Exception during successful commit acction", e);
            }
        }
    }

    @Override
    public boolean runOnRollBack(Runnable callback) {
        if (!isActiveSynchronisedTransaction()) {
            return false;
        }
        tlsTxInfo.get().rollbackActions.add(callback);
        return true;
    }

    @Override
    public boolean runOnSuccessfulCommit(Runnable callback) {
        if (!isActiveSynchronisedTransaction()) {
            return false;
        }
        tlsTxInfo.get().commitActions.add(callback);
        return true;
    }

    @Override
    public boolean isActiveSynchronisedTransaction() {
        return template.isActive();
    }

    void clear() {
        tlsTxInfo.remove();
    }

    void setTxTemplate(SimpleSalTransactionTemplate template) {
        this.template = template;
    }

    private static class TxInfo {
        private List<Runnable> rollbackActions = Lists.newArrayList();
        private List<Runnable> commitActions = Lists.newArrayList();
    }
}
