package com.atlassian.stash.internal.config;

import com.atlassian.stash.internal.db.DatabaseConstants;
import com.atlassian.stash.internal.jdbc.DataSourceConfiguration;
import com.atlassian.stash.internal.jdbc.SimpleDataSourceConfiguration;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.Properties;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class DataSourcePropertySerializerTest {

    private static String[] TEST_VALUES = new String[]{
            null,
            "",
            "blah",
            "//",
            "blah¡foo",
            "$_!d-=",
            "\\:"
    };

    @Parameterized.Parameters
    public static List<String[]> data() {
        List<String[]> data = Lists.newArrayList();
        // try the each of the strings defined above with every property
        for (int i = 0; i < TEST_VALUES.length; i++) {
            data.add(new String[] {
                    TEST_VALUES[i % TEST_VALUES.length],
                    TEST_VALUES[(i + 1) % TEST_VALUES.length],
                    TEST_VALUES[(i + 2) % TEST_VALUES.length],
                    TEST_VALUES[(i + 3) % TEST_VALUES.length]
            });
        }

        return data;
    }

    @Parameterized.Parameter(0)
    public String driverName;
    @Parameterized.Parameter(1)
    public String url;
    @Parameterized.Parameter(2)
    public String user;
    @Parameterized.Parameter(3)
    public String password;


    @Test
    public void testSerializationRoundTrip() throws Exception {
        DataSourceConfiguration config = new SimpleDataSourceConfiguration(driverName, url, user, password);

        DataSourcePropertySerializer serializer = new DataSourcePropertySerializer(config);

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try (Writer writer = new OutputStreamWriter(out, Charsets.UTF_8)) {
            serializer.writeTo(writer);
        }

        Properties props = new Properties();
        props.load(new ByteArrayInputStream(out.toByteArray()));
        assertEquals("driverName", Strings.nullToEmpty(driverName), props.getProperty(DatabaseConstants.PROP_JDBC_DRIVER));
        assertEquals("url", Strings.nullToEmpty(url), props.getProperty(DatabaseConstants.PROP_JDBC_URL));
        assertEquals("user", Strings.nullToEmpty(user), props.getProperty(DatabaseConstants.PROP_JDBC_USER));
        assertEquals("password", Strings.nullToEmpty(password), props.getProperty(DatabaseConstants.PROP_JDBC_PASSWORD));
    }
}
