/*
 * Copyright (c) eHealth
 */
package be.ehealth.business.kmehrcommons;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import org.junit.AfterClass;
import org.junit.Assert;

import be.ehealth.technicalconnector.config.ConfigFactory;
import be.ehealth.technicalconnector.exception.TechnicalConnectorException;
import be.ehealth.technicalconnector.session.Session;
import be.ehealth.technicalconnector.utils.ConnectorIOUtils;
import be.ehealth.technicalconnector.utils.ConnectorXmlUtils;
import be.fgov.ehealth.standards.kmehr.schema.v1.HcpartyType;
import be.fgov.ehealth.technicalconnector.tests.session.SessionInitializer;
import be.fgov.ehealth.technicalconnector.tests.utils.XmlAsserter;


/**
 * base class to test HcPartyUtils.
 * 
 * @author EHP
 * 
 */
public class AbstractTestHcPartyUtils {


    protected static void initHcPartyUtilProperties() throws Exception, IOException, TechnicalConnectorException {
        SessionInitializer.init("/be.ehealth.businessconnector.kmehrcommons.test.properties", false);


        Properties props = new Properties();
        props.load(ConnectorIOUtils.getResourceAsStream("/be.ehealth.businessconnector.kmehrcommons.test.properties"));

        for (Object key : props.keySet()) {
            if (key.toString().startsWith("kmehr")) {
                ConfigFactory.getConfigValidator().setProperty(key.toString(), props.getProperty(key.toString()));
            }
        }
    }

    @AfterClass
    public static void tearDown() throws Exception {
        Session.getInstance().unloadSession();
    }

    /**
     * 
     */
    public AbstractTestHcPartyUtils() {
        super();
    }

    /**
     * @param expectedResult
     * @param results
     */
    protected void checkResults(List<String> expectedResult, List<HcpartyType> results) {
        Assert.assertEquals(expectedResult.size(), results.size());

        for (HcpartyType hcparty : results) {
            checkHcpartyInList(expectedResult, hcparty);
        }
    }

    protected void checkHcpartyXml(String expectedXml, HcpartyType hcparty) {
        Assert.assertTrue(XmlAsserter.isSimilar(expectedXml, convertToXmlString(hcparty)));
    }

    /**
     * @param expectedResult
     * @param hcparty
     */
    private void checkHcpartyInList(List<String> expectedResult, HcpartyType hcparty) {
        String xml = convertToXmlString(hcparty);
        boolean expected = false;
        for (String expectedXML : expectedResult) {
            if (XmlAsserter.isSimilar(expectedXML, xml)) {
                expected = true;
            }
        }
        Assert.assertTrue("following xmlString retrieved , but not in expectedlist:\n " + xml, expected);
    }

    /**
     * @param hcparty
     * @return
     */
    private String convertToXmlString(HcpartyType hcparty) {
        return ConnectorXmlUtils.flatten(new String(ConnectorXmlUtils.toByteArray(hcparty)));
    }

}