/*
 * Copyright (c) eHealth
 */
package be.fgov.ehealth.technicalconnector.tests.utils;

import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.joda.time.DateTime;
import org.junit.Assume;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.ehealth.technicalconnector.beid.BeIDInfo;
import be.ehealth.technicalconnector.exception.TechnicalConnectorException;
import be.ehealth.technicalconnector.session.Session;
import be.ehealth.technicalconnector.utils.ConnectorIOUtils;
import be.ehealth.technicalconnector.utils.DateUtils;


/**
 * Class containt an list of assumes.
 * 
 * @author EHP
 */
public final class AssumeTools {

    private static final Logger LOG = LoggerFactory.getLogger(AssumeTools.class);

    private AssumeTools() {
        throw new UnsupportedOperationException();
    }

    public static void isEIDEnabled() {
        try {
            BeIDInfo.getInstance("EidIsPresent");
        } catch (TechnicalConnectorException e) {
            LOG.warn("EidIsNotPresent Reason:[" + e.getMessage() + "]");
            Assume.assumeNoException(e);
        }
    }

    public static void isUser(String... ssins) {
        isEIDEnabled();
        try {
            String currentSSIN = BeIDInfo.getInstance("EidIsPresent").getIdentity().getNationalNumber();
            Assume.assumeTrue(ArrayUtils.contains(ssins, currentSSIN));
        } catch (TechnicalConnectorException e) {
            LOG.warn("EidIsNotPresent Reason:[" + e.getMessage() + "]");
            Assume.assumeNoException(e);
        }
    }

    public static void isPersPhysician() {
        try {
            boolean isDoctor = false;
            List<String> attributeValues = SAMLTokenUtils.getAttributeValue(Session.getInstance().getSession().getSAMLToken().getAssertion(), "urn:be:fgov:person:ssin:doctor:boolean");
            if (attributeValues.size() == 1) {
                isDoctor = Boolean.parseBoolean(attributeValues.get(0));
            }
            Assume.assumeTrue(isDoctor);
        } catch (TechnicalConnectorException e) {
            LOG.warn("UserIsNotPersPhysician Reason:[" + e.getMessage() + "]");
            Assume.assumeNoException(e);
        }
    }

    public static void isUserInteractionEnabled() {
        LOG.info("GraphicsEnvironment.isHeadless()?");
        Assume.assumeTrue(!GraphicsEnvironment.isHeadless());
    }

    public static void isInternetConnectionEnabled() {
        File flagFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "NoInternetConnection");
        if (flagFile.exists() && new DateTime(flagFile.lastModified()).plusHours(3).isAfterNow()) {
            LOG.warn("NoInternetConnection Reason: flag detected creationTime " + DateUtils.printDateTime(new DateTime(flagFile.lastModified())));
            Assume.assumeTrue(false);
            return;
        }
        InputStream stream = null;
        try {
            String address = "http://www.google.be";
            URL endpoint = new URL(address);
            HttpURLConnection conURL = (HttpURLConnection) endpoint.openConnection();
            conURL.setConnectTimeout(5000);
            conURL.setReadTimeout(5000);
            stream = conURL.getInputStream();
            Assume.assumeNotNull(stream);
            delete(flagFile);
            LOG.info("InternetConnection detected. Url [" + address + "]");
        } catch (Exception e) {
            LOG.warn("NoInternetConnection Reason:[" + e.getMessage() + "]");
            delete(flagFile);
            try {
                LOG.info("Stale flag [" + flagFile.getAbsolutePath() + "] status " + flagFile.createNewFile());
            } catch (IOException io) {
                LOG.error("Unable to create flag.");
            }
            Assume.assumeNoException(e);
        } finally {
            ConnectorIOUtils.closeQuietly(stream);
        }
    }

    /**
     * @param flagFile
     */
    private static void delete(File flagFile) {
        if (flagFile.exists()) {
            flagFile.delete();
        }
    }
}
