package com.atlassian.stash.internal.util;

import com.atlassian.bitbucket.util.ProxyUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.core.InfrastructureProxy;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.concurrent.CountDownLatch;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
public class TransactionAwareLatchedInvocationHandlerTest {

    private String transactionDelegate = "transactionResource";
    private String targetDelegate = "targetResource";
    @Mock
    private CountDownLatch latch;

    private InfrastructureProxy proxy;

    @Before
    public void setUp() throws Exception {
        proxy = ProxyUtils.createProxy(InfrastructureProxy.class, new TransactionAwareLatchedInvocationHandler(targetDelegate, latch, transactionDelegate));
    }

    @Test
    public void testGetWrappedObjectWithNoTransaction() throws Exception {
        assertEquals(targetDelegate, proxy.getWrappedObject());
    }

    @Test
    public void testGetWrappedObjectWithinTransaction() throws Exception {
        TransactionSynchronizationManager.bindResource(transactionDelegate, "blah");
        assertEquals(transactionDelegate, proxy.getWrappedObject());
        TransactionSynchronizationManager.unbindResource(transactionDelegate);
        testGetWrappedObjectWithNoTransaction();
    }
}
