package at.gv.util.client.omsp;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;

import at.gv.util.MiscUtil;
import at.gv.util.xsd.omsp.SignedStatusResponse;

public class OMSPClient {

	public static SignedStatusResponse checkMandateStatus(String serviceURL, String mandateId, Date date) throws OMSPClientException {
		MiscUtil.assertNotNull(serviceURL, "serviceURL");
		MiscUtil.assertNotNull(mandateId, "mandateId");
		HttpClient httpclient = HttpClients.createDefault();		
		HttpGet  method = new HttpGet(serviceURL);
		if (date != null) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
			mandateId += "+" + sdf.format(date);
		}
		try {
			URI uri = new URIBuilder(method.getURI()).addParameter("", mandateId).build();		
			method.setURI(uri);
					
			HttpResponse response = httpclient.execute(method);
			
			if (response.getStatusLine().getStatusCode() != 200) {
				throw new OMSPClientException("Response code " + response.getStatusLine().getStatusCode() + " returned. Must be 200.");
				
	    }
		
	    JAXBContext ctx = JAXBContext.newInstance(SignedStatusResponse.class.getPackage().getName());
	    return (SignedStatusResponse) ctx.createUnmarshaller().unmarshal(response.getEntity().getContent());
	    
    } catch (IOException e) {
    	throw new OMSPClientException(e);
    } catch (JAXBException e) {
    	throw new OMSPClientException(e);
    } catch (URISyntaxException e) {
    	throw new OMSPClientException(e);
	}
	}
	
}