package com.atlassian.stash.internal.maintenance;

import com.atlassian.event.api.EventPublisher;
import com.atlassian.johnson.event.AddEvent;
import com.atlassian.johnson.event.RemoveEvent;
import com.atlassian.scheduler.SchedulerServiceException;
import com.atlassian.scheduler.core.LifecycleAwareSchedulerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class DefaultMaintenanceModeHelperTest {

    @Mock
    private JohnsonMaintenanceEvent event;
    @Mock
    private EventPublisher eventPublisher;
    @InjectMocks
    private DefaultMaintenanceModeHelper helper;
    @Mock
    private LifecycleAwareSchedulerService schedulerService;

    @Test
    public void testLock() throws Exception {
        try {
            helper.lock(event);
        } finally { //Done in a finally block to allow testLockSwallowsSchedulerExceptions to reuse it
            InOrder ordered = inOrder(eventPublisher, schedulerService);
            ordered.verify(schedulerService).standby();
            ordered.verify(eventPublisher).publish(isA(AddEvent.class));
        }
    }

    @Test
    public void testLockSwallowsSchedulerExceptions() throws Exception {
        doThrow(SchedulerServiceException.class).when(schedulerService).standby();

        testLock();
    }

    @Test
    public void testUnlock() throws Exception {
        try {
            helper.unlock(event);
        } finally { //Done in a finally block to allow testUnlockSwallowsSchedulerExceptions to reuse it
            InOrder ordered = inOrder(eventPublisher, schedulerService);
            ordered.verify(eventPublisher).publish(isA(RemoveEvent.class));
            ordered.verify(schedulerService).start();
        }
    }

    @Test
    public void testUnlockSwallowsSchedulerExceptions() throws Exception {
        doThrow(SchedulerServiceException.class).when(schedulerService).start();

        testUnlock();
    }
}
