package com.atlassian.stash.internal.plugin;

import com.atlassian.sal.api.pluginsettings.PluginSettings;
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.ApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import static com.atlassian.stash.internal.plugin.DefaultPluginSettingsFactory.GLOBAL_SETTING_NAMESPACE;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class DefaultPluginSettingsFactoryTest {

    @Mock
    private ApplicationContext applicationContext;
    @Mock
    private PluginSettingDao dao;
    @Mock
    private PlatformTransactionManager platformTransactionManager;
    @Mock
    private PluginSettings pluginSettings;

    private DefaultPluginSettingsFactory factory;

    @Before
    public void setUp() throws Exception {
        factory = new DefaultPluginSettingsFactory(applicationContext, dao, platformTransactionManager);
        when(applicationContext.getBean(eq("pluginSettingsPrototype"), same(dao), anyString(),
                any(TransactionTemplate.class), any(TransactionTemplate.class))).thenReturn(pluginSettings);
    }

    @Test
    public void testCreateGlobalSettings() throws Exception {
        assertNotNull(factory.createGlobalSettings());

        verify(applicationContext, times(1)).getBean(eq("pluginSettingsPrototype"), same(dao),
                eq(GLOBAL_SETTING_NAMESPACE), any(TransactionTemplate.class), any(TransactionTemplate.class));

        // verify that the global settings are only created once
        assertNotNull(factory.createGlobalSettings());
        assertNotNull(factory.createGlobalSettings());

        verify(applicationContext, times(1)).getBean(eq("pluginSettingsPrototype"), same(dao),
                eq(GLOBAL_SETTING_NAMESPACE), any(TransactionTemplate.class), any(TransactionTemplate.class));
    }

    @Test
    public void testCreateSettingsForKey() throws Exception {
        assertNotNull(factory.createSettingsForKey("plugin-key"));
        verify(applicationContext, times(1)).getBean(eq("pluginSettingsPrototype"), same(dao), eq("plugin-key"),
                any(TransactionTemplate.class), any(TransactionTemplate.class));
    }
}