/*
 * Copyright (c) eHealth
 */
package be.ehealth.technicalconnector.config.impl;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;

import java.io.File;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Test;

import be.ehealth.technicalconnector.config.ConfigFactory;
import be.ehealth.technicalconnector.config.ConfigValidator;
import be.ehealth.technicalconnector.config.ConfigurationModule;


/**
 * Test configuration module {@link ConfigurationModuleSystemProps}
 * 
 * @author EHP
 * 
 */
public class ConfigurationModuleSystemPropsTest {

    private static final String LF = System.getProperty("line.separator");

    private ConfigValidator config = ConfigFactory.getConfigValidator();

    private ConfigurationModule module = new ConfigurationModuleSystemProps();

    @After
    public void unload() throws Exception {
        module.unload();
    }

    @Test
    public void full() throws Exception {
        String uuid = UUID.randomUUID().toString();
        File tempfile = createFile();
        FileUtils.write(tempfile, ConfigurationModuleSystemProps.SYSTEMPROP_ROOTKEY + ".1=os.name=Windows " + uuid + LF, true);
        FileUtils.write(tempfile, ConfigurationModuleSystemProps.SYSTEMPROP_ROOTKEY + ".2=os.version=" + uuid + LF, true);


        ConfigFactory.setConfigLocation(tempfile.getAbsolutePath());


        module.init(config.getConfig());

        assertThat(System.getProperty("os.name"), equalTo("Windows " + uuid));
        assertThat(System.getProperty("os.version"), equalTo(uuid));

        module.unload();

        assertThat(System.getProperty("os.name"), not(equalTo("Windows " + uuid)));
        assertThat(System.getProperty("os.version"), not(equalTo(uuid)));

    }

    @Test
    public void doubleDelimiter() throws Exception {
        File tempfile = createFile();
        FileUtils.write(tempfile, ConfigurationModuleSystemProps.SYSTEMPROP_ROOTKEY + ".1=double.delimiter=6=5" + LF, true);
        
        module.init(config.getConfig());
        
        assertThat(System.getProperty("double.delimiter"), equalTo("6=5"));

    }


    private static File createFile() throws Exception {
        File tempfile = File.createTempFile("systemprops", "properties");
        tempfile.deleteOnExit();
        ConfigFactory.setConfigLocation(tempfile.getAbsolutePath());
        return tempfile;
    }

    @Test(expected = IllegalArgumentException.class)
    public void noDelimiter() throws Exception {
        String uuid = UUID.randomUUID().toString();
        File tempfile = createFile();
        FileUtils.write(tempfile, ConfigurationModuleSystemProps.SYSTEMPROP_ROOTKEY + ".1=os.version" + uuid + LF, true);

        ConfigFactory.setConfigLocation(tempfile.getAbsolutePath());

        module.init(config.getConfig());

    }


}
