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

import java.awt.*;
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 be.ehealth.technicalconnector.beid.BeIDFactory;
import org.apache.commons.lang3.ArrayUtils;
import org.joda.time.DateTime;
import org.junit.Assume;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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 {
            BeIDFactory.getBeIDInfo("EidIsPresent",false);
        } catch (TechnicalConnectorException e) {
            LOG.warn("EidIsNotPresent Reason:[" + e.getMessage() + "]");
            Assume.assumeNoException(e);
        }
    }

    public static void isUser(String... ssins) {
        isEIDEnabled();
        try {
            String currentSSIN =  BeIDFactory.getBeIDInfo("EidIsPresent",false)
                                         .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() throws TechnicalConnectorException {
        File flagFile = ConnectorIOUtils.createTempFile("NoInternetConnection", false);
        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();
        }
    }
}
