package com.atlassian.stash.internal.scm.protocol.http;

import com.atlassian.soy.renderer.SoyTemplateRenderer;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.notNull;
import static org.mockito.Matchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class HttpScmHostingFormFragmentTest {

    @Mock
    private ApplicationPropertiesService applicationPropertiesService;
    @Mock
    private SoyTemplateRenderer soyTemplateRenderer;
    @InjectMocks
    private HttpScmHostingFormFragment formFragment;

    @SuppressWarnings("unchecked")
    @Test
    public void testDoView() throws Exception {
        when(applicationPropertiesService.isHttpScmHostingEnabled()).thenReturn(true);

        Appendable buffer = mock(Appendable.class);
        Map<String, Object> context = new HashMap<>(); // the fragment's doView() requires a mutable Map
        formFragment.doView(buffer, context);

        ArgumentCaptor<Map> templateContextCaptor = ArgumentCaptor.forClass(Map.class);
        verify(soyTemplateRenderer).render(same(buffer), notNull(String.class),
                notNull(String.class), templateContextCaptor.capture());
        Map<String, Object> templateContext = templateContextCaptor.getValue();
        assertThat(templateContext, hasEntry("enabled", (Object) true));
        assertThat(templateContext, hasEntry(equalTo("product"), notNullValue()));
    }

    @Test
    public void testExecuteWhenDisablingHttpScmHosting() throws Exception {
        Map<String, String[]> parameters = Collections.emptyMap();
        formFragment.execute(parameters, Collections.<String, Object>emptyMap());
        verify(applicationPropertiesService).setHttpScmHostingEnabled(false);
    }

    @Test
    public void testExecuteWhenEnablingHttpScmHosting() throws Exception {
        Map<String, String[]> parameters = Collections.singletonMap("httpEnabled", new String[]{"on"});
        formFragment.execute(parameters, Collections.<String, Object>emptyMap());
        verify(applicationPropertiesService).setHttpScmHostingEnabled(true);
    }

}