package com.atlassian.bitbucket.installer;

import com.atlassian.bitbucket.installer.analytics.PingbackClient;
import com.google.common.collect.ImmutableMap;
import com.install4j.api.context.InstallerContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

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

@RunWith(MockitoJUnitRunner.class)
public class TrackerTest {
    private static final String EVENT_NAME = "test-event";
    private static final String INSTALLATION_ID = "ABC123";
    private static final String OS = Platform.current().toString();
    private static final String PRODUCT = "stash";
    private static final String VERSION = "ver";
    private static final Map<String, String> OS_MAP = ImmutableMap.of("os", OS);

    private Tracker tracker;

    @Mock
    private PingbackClient mockPingbackClient;

    @Before
    public void setUpClass() throws Exception {
        tracker = new Tracker(mockPingbackClient);
        when(mockPingbackClient.pingback(eq(PRODUCT), eq(VERSION), eq(INSTALLATION_ID), eq(EVENT_NAME), eq(OS_MAP)))
                .thenReturn(200);
    }

    @Test
    public void testTrack() throws Exception {
        InstallationDetails mockDetails = mock(InstallationDetails.class);
        when(mockDetails.getInstallationId()).thenReturn(INSTALLATION_ID);

        InstallerContext mockContext = mock(InstallerContext.class);
        when(mockContext.getVariable("sys.version")).thenReturn(VERSION);
        when(mockContext.getVariable("installation.details")).thenReturn(mockDetails);

        tracker.track(mockContext, EVENT_NAME);
        verifyPingbackClientCalled();
    }

    @Test
    public void testTrackSynchronously() throws Exception {
        tracker.trackSynchronously(EVENT_NAME, OS, VERSION, INSTALLATION_ID);
        verifyPingbackClientCalled();
    }

    private void verifyPingbackClientCalled() throws URISyntaxException, IOException {
        verify(mockPingbackClient, timeout(100).times(1)).pingback(eq(PRODUCT), eq(VERSION), eq(INSTALLATION_ID), eq(EVENT_NAME), eq(OS_MAP));
    }

}