package it.com.atlassian.stash.installer.host;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.util.List;
import java.util.Map;

import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

public class ValidatePingbackTest {

    @Test
    public void testPingbacksSent() throws Exception {
        String pingbackLogFilename = System.getProperty("installerPingbackLog");
        if (pingbackLogFilename == null) {
            fail(String.format("Expected installer pingback log location in env var 'installerPingbackLog'"));
        }

        // On Windows we might still get a path with / which fails, so we replace with the proper file separator
        pingbackLogFilename = pingbackLogFilename.replace("/", File.separator);

        File pingbackLogFile = new File(pingbackLogFilename);
        if (!pingbackLogFile.exists()) {
            fail(String.format("Pingback log file not found at %s", pingbackLogFilename));
        }

        String pingbackLogJSON = FileUtils.readFileToString(pingbackLogFile, Charsets.UTF_8);

        ObjectMapper mapper = new ObjectMapper();
        List<Pingback> pingbacks = mapper.readValue(pingbackLogJSON, new TypeReference<List<Pingback>>() {
        });

        List<String> actualEvents = Lists.transform(pingbacks, p -> p.params.get("pg"));

        assertThat(actualEvents, hasItems(
                "installer-welcome",
                "installer-install-directory",
                "installer-home-directory",
                "installer-type-install",
                "installer-set-ports",
                "installer-custom-ports",
                "installer-summary",
                "installer-launch-stash-prompt",
                "installer-launch-stash-success"
        ));
    }

    private static class Pingback {
        public String date;
        public Map<String, String> params;
    }

}
