package com.atlassian.bitbucket.web.conditions;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

import java.util.Collections;

import static com.atlassian.bitbucket.web.conditions.HasDatabaseOfTypeCondition.TYPE;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doAnswer;

@RunWith(MockitoJUnitRunner.class)
public class HasDatabaseOfTypeConditionTest {

    private static final String HSQL_URL = "jdbc:hsqldb:/path/to/home/data/db;shutdown=true";
    private static final String MYSQL_URL = "jdbc:mysql://localhost:3306/stash_db";
    private static final String POSTGRESQL_URL = "jdbc:postgresql://localhost:5432/stash_db";

    @Mock
    private ApplicationPropertiesService propertiesService;
    @InjectMocks
    private HasDatabaseOfTypeCondition condition;

    private String currentJdbcUrl = HSQL_URL;

    @Before
    public void setup() throws Exception {
        doAnswer(new Answer() {
            public Object answer(InvocationOnMock invocation) throws Throwable {
                return currentJdbcUrl;
            }
        }).when(propertiesService).getJdbcUrl();
    }

    @Test(expected = PluginParseException.class)
    public void testInitWithNoParams() throws Exception {
        condition.init(Collections.<String, String>emptyMap());
    }

    @Test
    public void testInitWithTypeParam() throws Exception {
        condition.init(Collections.singletonMap(TYPE, "mysql"));
        condition.init(Collections.singletonMap(TYPE, "mysql,hsqldb"));
    }

    @Test
    public void testShouldDisplay() throws Exception {
        condition.init(Collections.singletonMap(TYPE, "mysql"));
        currentJdbcUrl = HSQL_URL;
        assertFalse("Should not match hqsldb", condition.shouldDisplay(Collections.<String, Object>emptyMap()));
        currentJdbcUrl = MYSQL_URL;
        assertTrue("Should match mysql", condition.shouldDisplay(Collections.<String, Object>emptyMap()));
        condition.init(Collections.singletonMap(TYPE, "mysql,hsqldb"));
        currentJdbcUrl = HSQL_URL;
        assertTrue("Should match hqsldb", condition.shouldDisplay(Collections.<String, Object>emptyMap()));
        currentJdbcUrl = MYSQL_URL;
        assertTrue("Should match mysql", condition.shouldDisplay(Collections.<String, Object>emptyMap()));
        currentJdbcUrl = POSTGRESQL_URL;
        assertFalse("Should not match postgres", condition.shouldDisplay(Collections.<String, Object>emptyMap()));
    }
}
