/*
 * Copyright (c) eHealth
 */
package be.ehealth.businessconnector.test.genericasync.handlers;

import be.ehealth.businessconnector.genericasync.handlers.IncomingSecurityHandler;
import be.ehealth.technicalconnector.config.domain.Duration;
import be.ehealth.technicalconnector.exception.TechnicalConnectorException;
import be.ehealth.technicalconnector.utils.DateUtils;
import be.ehealth.technicalconnector.ws.ServiceFactory;
import be.ehealth.technicalconnector.ws.domain.GenericRequest;
import be.ehealth.technicalconnector.ws.domain.HandlerChain;
import be.ehealth.technicalconnector.ws.domain.HandlerPosition;
import be.fgov.ehealth.technicalconnector.tests.junit.rule.HttpServerStubRule;
import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertEquals;


/**
 * Unit test for validating {@link IncomingSecurityHandler}
 * 
 * @author EHP
 *
 */
public class IncomingSecurityHandlerTest {

    @Rule
    public HttpServerStubRule server = new HttpServerStubRule();

    /**
     * Normal message
     */
    @Test
    public void normal() throws Exception {
        invoke(new DateTime(), new DateTime().plusHours(1), new Duration(5, TimeUnit.MINUTES), new Duration(5, TimeUnit.MINUTES));
    }

    /**
     * Normal message created in the past message.
     */
    @Test
    public void inPast() throws Exception {
        try {
            invoke(new DateTime().minusHours(2), new DateTime().minusHours(1), new Duration(5, TimeUnit.MINUTES), new Duration(5, TimeUnit.MINUTES));
        } catch (TechnicalConnectorException e) {
            assertEquals("Invalid timestamp: The message timestamp has expired", e.getCause().getMessage());
        }
    }

    /**
     * Download time of 1 hour
     */
    @Test
    public void large() throws Exception {
        invoke(new DateTime().minusHours(1), new DateTime().plusDays(1), new Duration(61, TimeUnit.MINUTES), new Duration(5, TimeUnit.MINUTES));
    }


    private void invoke(DateTime created, DateTime expires, Duration timestampTTL, Duration timeStampFutureTTL) throws Exception {
        server.add("/full/timestamp", "/stub/wsse_ts.xml");
        String url = server.getContentUrl("/full/timestamp", new String[]{"created", DateUtils.printDateTime(created)}, new String[]{"expires", DateUtils.printDateTime(expires)});

        GenericRequest req = new GenericRequest();
        req.setPayload("<echo xmlns=\"urn:be:fgov:ehealth:echo:v1\"></echo>");
        req.setEndpoint(url);
        HandlerChain chain = new HandlerChain();
        req.addHandlerChain(chain.register(HandlerPosition.AFTER, new IncomingSecurityHandler(timestampTTL, timeStampFutureTTL)));

        ServiceFactory.getGenericWsSender().send(req);
    }


}
