package com.atlassian.stash.internal.mode;

import com.atlassian.bitbucket.server.ApplicationMode;
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.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class ApplicationModeConditionTest {
    @Mock
    private ConditionContext context;
    @Mock
    private Environment environment;
    @Mock
    private AnnotatedTypeMetadata metadata;

    @Before
    public void setUp() throws Exception {
        when(context.getEnvironment()).thenReturn(environment);
        when(environment.getProperty("application.mode")).thenReturn(ApplicationMode.DEFAULT.getId());
    }

    @Test
    public void testDefaultModeAnnotatedWithDefault() throws Exception {
        when(metadata.isAnnotated(DefaultApplicationMode.class.getName())).thenReturn(true);
        assertTrue(new ApplicationModeCondition().matches(context, metadata));
        verify(metadata).isAnnotated(DefaultApplicationMode.class.getName());
    }

    @Test
    public void testDefaultModeAnnotatedWithMirror() throws Exception {
        when(metadata.isAnnotated(MirrorApplicationMode.class.getName())).thenReturn(true);
        assertFalse(new ApplicationModeCondition().matches(context, metadata));
        verify(metadata).isAnnotated(DefaultApplicationMode.class.getName());
    }

    @Test
    public void testMirrorModeAnnotatedWithMirror() throws Exception {
        when(environment.getProperty("application.mode")).thenReturn(ApplicationMode.MIRROR.getId());
        when(metadata.isAnnotated(MirrorApplicationMode.class.getName())).thenReturn(true);
        assertTrue(new ApplicationModeCondition().matches(context, metadata));
        verify(metadata).isAnnotated(MirrorApplicationMode.class.getName());
    }

    @Test
    public void testMirrorModeAnnotatedWithDefault() throws Exception {
        when(environment.getProperty("application.mode")).thenReturn(ApplicationMode.MIRROR.getId());
        when(metadata.isAnnotated(DefaultApplicationMode.class.getName())).thenReturn(true);
        assertFalse(new ApplicationModeCondition().matches(context, metadata));
        verify(metadata).isAnnotated(MirrorApplicationMode.class.getName());
    }
}