package gov.wisconsin.wijis.services.protectionorder;


import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import protectionorder.response.gov.ojp.it.jxdm._3_0_3.AddressType;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.CaseDocketID;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.CaseType;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.CourtOrderType;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.LocationType;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.PersonNameTextType;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.PersonNameType;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.TextType;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.proxy.fips_6_4._1.USCountyCodeType;
import protectionorder.response.gov.ojp.it.jxdm._3_0_3.proxy.xsd._1.Date;
import protectionorder.response.gov.wisconsin.wijis.specs.schemas.court_docs.protection_order.v1_1._2007_10_19.document.ObjectFactory;
import protectionorder.response.gov.wisconsin.wijis.specs.schemas.court_docs.protection_order.v1_1._2007_10_19.document.ProtectionOrderDescriptiveMetadataType;
import protectionorder.response.gov.wisconsin.wijis.specs.schemas.court_docs.protection_order.v1_1._2007_10_19.document.ProtectionOrderDocumentType;
import protectionorder.response.gov.wisconsin.wijis.specs.schemas.court_docs.protection_order.v1_1._2007_10_19.document.ProtectionOrderSubjectType;
import protectionorder.response.gov.wisconsin.wijis.specs.schemas.court_docs.protection_order.v1_1._2007_10_19.document.ProtectionOrderType;

public class ProtectionOrderServiceHelperMethodsResponse
{
	public static Document createResponseMessage(protectionorder.issue.gov.wisconsin.wijis.specs.schemas.court_docs.protection_order.v1_1._2007_10_19.document.ProtectionOrderDocumentType protectionOrderInputDocument)
	{   
		ProtectionOrderDocumentType protectionOrderResponseDocument = new ProtectionOrderDocumentType();
		
		ObjectFactory objFactory = new ObjectFactory();
		ProtectionOrderType protectionOrderResponseType = objFactory.createProtectionOrderType();
		
		//Set The ID of the response document to what was in the input document
		protectionOrderResponseType.setId(protectionOrderInputDocument.getId());
		
		//Set The Warrant ID of the Warrant Reponse Type to what was in the input document
		protectionOrderResponseType.setId(protectionOrderInputDocument.getProtectionOrder().getId());
		
		//START ProtectionOrderDescriptiveMetadata
		//TODO Need to set the date and time properly here, I don't know how to do it.  Tony, can you look at this block?  
		ProtectionOrderDescriptiveMetadataType responseMetaData = new ProtectionOrderDescriptiveMetadataType();
		
		GregorianCalendar calendar = new GregorianCalendar();
		
		XMLGregorianCalendar date = null;
		try
		{
			date = DatatypeFactory.newInstance().newXMLGregorianCalendar();
			
			date.setTime(calendar.getTime().getHours(), calendar.getTime().getMinutes(), calendar.getTime().getSeconds());
		} 
		catch (DatatypeConfigurationException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Date currentDate = new Date();
        try
        {
                currentDate.setValue(DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar()));
        }
        catch (Exception e)
        {
                e.printStackTrace();
        }              
        responseMetaData.setDocumentReceivedDate(currentDate);
        
		protectionOrderResponseDocument.setProtectionOrderDescriptiveMetadata(responseMetaData);
		//END ProtectionOrderDescriptiveMetadata		
		
		//START Set the CourtOrderDesignatedLocation
		//The location in the incoming document is an array, we just get the first element in this example
		String incomingCounty = protectionOrderInputDocument.getProtectionOrder().getCourtOrderDesignatedLocation().getLocationAddress().get(0).getLocationCountyName().getValue();
		String incomingCountyCode = protectionOrderInputDocument.getProtectionOrder().getCourtOrderDesignatedLocation().getLocationAddress().get(0).getLocationCountyCode().getValue();
		
		USCountyCodeType countyCode = new USCountyCodeType();
		countyCode.setValue(incomingCountyCode);
		
		AddressType locationAddress = new AddressType();
		locationAddress.setLocationCountyName(returnResponseTextType(incomingCounty));
		locationAddress.setLocationCountyCode(countyCode);
		
		LocationType location = new LocationType();
		location.setLocationAddress(locationAddress);
		
		CourtOrderType courtOrderDesignatedLocation = new CourtOrderType();
		courtOrderDesignatedLocation.setCourtOrderDesignatedLocation(location);
		
		protectionOrderResponseType.setCourtOrderDesignatedLocation(location);
		//END Set the CourtOrderDesignatedLocation
		
		//START Case
		CaseDocketID caseDocket = new CaseDocketID();
		caseDocket.setID(protectionOrderInputDocument.getProtectionOrder().getCase().getCaseDocketID().getID());
		
		CaseType caseType = new CaseType();
		caseType.setCaseDocketID(caseDocket);

		protectionOrderResponseType.setCase(caseType);
		//END Case
		
		//START Warrant Subject
		
        // ProtectionOrderSubjectType in the issue document is explicitly referenced by package name to avoid collisions.
		ProtectionOrderSubjectType responseProtectionOrderSubject = new ProtectionOrderSubjectType();
		List<protectionorder.issue.gov.wisconsin.wijis.specs.schemas.court_docs.protection_order.v1_1._2007_10_19.document.ProtectionOrderSubjectType> protectionOrderSubjectList = protectionOrderInputDocument.getProtectionOrder().getProtectionOrderSubject();
		
		if(protectionOrderSubjectList != null && protectionOrderSubjectList.size() >0)
		{
			responseProtectionOrderSubject.setId(protectionOrderSubjectList.get(0).getId());
			
			PersonNameTextType personGivenNameTextTypeHolder = new PersonNameTextType();
			personGivenNameTextTypeHolder.setValue(protectionOrderInputDocument.getProtectionOrder().getProtectionOrderSubject().get(0).getPersonName().getPersonGivenName().getValue());
			
			PersonNameType personName = new PersonNameType();
			personName.setPersonGivenName(personGivenNameTextTypeHolder);
			
			//Set the Person Middle Name.
			//since both issue and response middle name types are accessed, the person middle name in the issue document is explicitly referenced by package name to avoid collisions.
			for (protectionorder.issue.gov.ojp.it.jxdm._3_0_3.PersonNameTextType personNameTextTypeInputMiddleName : protectionOrderInputDocument.getProtectionOrder().getProtectionOrderSubject().get(0).getPersonName().getPersonMiddleName())
			{   
				PersonNameTextType personMiddleNameTextTypeHolder = new PersonNameTextType();
				personMiddleNameTextTypeHolder.setValue(personNameTextTypeInputMiddleName.getValue());
				personName.getPersonMiddleName().add(personMiddleNameTextTypeHolder);
			}
			
			//Set the Person Sur Name
			PersonNameTextType personSurNameTextTypeHolder = new PersonNameTextType();
			personSurNameTextTypeHolder.setValue(protectionOrderInputDocument.getProtectionOrder().getProtectionOrderSubject().get(0).getPersonName().getPersonSurName().getValue());
			personName.setPersonSurName(personSurNameTextTypeHolder);
			
			//Set the person name suffix
			personName.setPersonSuffixName(returnResponseTextType(protectionOrderInputDocument.getProtectionOrder().getProtectionOrderSubject().get(0).getPersonName().getPersonSuffixName().getValue()));

			responseProtectionOrderSubject.setPersonName(personName);
			
			//Set subject birth date
			Date personBirthDate = new Date();
			XMLGregorianCalendar incomingBirthDate = protectionOrderInputDocument.getProtectionOrder().getProtectionOrderSubject().get(0).getPersonBirthDate().getValue();
			personBirthDate.setValue(incomingBirthDate);
			
			responseProtectionOrderSubject.setPersonBirthDate(personBirthDate);
			
			protectionOrderResponseType.setProtectionOrderSubject(responseProtectionOrderSubject);
			//END Protection Order Subject
		}
		else
		{
			System.out.println("No Protection Order Subject to process");
		}
			
			//Add the Warrant Response to the Warrant Response Document
			protectionOrderResponseDocument.setProtectionOrder(protectionOrderResponseType);
			
			//Set up the DOM variables used to create the response
			DocumentBuilder builder;
			Document doc = null;
			Document document = null;
			try {

				//Create a new DOM builder and Document
				builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				document = builder.newDocument();

				//Create a SubmissionResponse root element in the DOM
				Element rootElement = document.createElementNS("http://wijis.wisconsin.gov/services/ProtectionOrderService/",
						"SubmissionResponse");
				document.appendChild(rootElement);

				//Create another DOM builder and Document for the WarrantResponseDocument
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				dbf.setNamespaceAware(true);
				doc = dbf.newDocumentBuilder().newDocument();

				//Create a JaxB Marshaller
				JAXBContext marshallContext;
				try {
					marshallContext = JAXBContext.newInstance(ProtectionOrderDocumentType.class);
					Marshaller marshaller = marshallContext.createMarshaller();
					
					//Create a JAXB element for the Warrant Response Document
					JAXBElement jaxbElement = new JAXBElement(
							new QName(
									"http://wijis.wisconsin.gov/specs/schemas/court-docs/protection-order/v1.1/2007-10-19/document/",
									"ProtectionOrderResponseDocument", "doc"),
									protectionorder.response.gov.wisconsin.wijis.specs.schemas.court_docs.protection_order.v1_1._2007_10_19.document.ProtectionOrderDocumentType.class,
									protectionOrderResponseDocument);

					//Marshall this element into the Submission Repsonse Element
					marshaller.marshal(jaxbElement, rootElement);

				} catch (JAXBException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			//Return the DOM document
			return document;
		}
	
	/**
	 * This helper method returns a response TextType from a string
	 * @param value
	 * @return TextType
	 */
	
	public static TextType returnResponseTextType(String value)
	{
		TextType returnValue = new TextType();
		returnValue.setValue(value);
		return returnValue;
	}
}
