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

import java.util.concurrent.TimeUnit;

import javax.xml.ws.ProtocolException;

import org.joda.time.DateTime;
import org.junit.Rule;
import org.junit.Test;

import be.ehealth.technicalconnector.config.domain.Duration;
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;


/**
 * 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(expected = ProtocolException.class)
    public void inPast() throws Exception {
        invoke(new DateTime().minusHours(2), new DateTime().minusHours(1), new Duration(5, TimeUnit.MINUTES), new Duration(5, TimeUnit.MINUTES));
    }

    /**
     * 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.setHandlerChain(chain.register(HandlerPosition.AFTER, new IncomingSecurityHandler(timestampTTL, timeStampFutureTTL)));

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


}
