package eu.stork.documentservice;

import java.util.Properties;
import java.util.UUID;

import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;

import org.apache.log4j.Logger;

import com.sun.tools.ws.processor.model.ModelException;

import eu.stork.documentservice.data.DatabaseConnector;
import eu.stork.documentservice.data.DatabaseConnectorMySQLImpl;
import eu.stork.documentservice.model.TempDocumentModel;
import eu.stork.documentservice.utils.XmlHelper;

@MTOM(threshold=500)
@WebService(endpointInterface = "eu.stork.documentservice.SPDocumentService", targetNamespace = "http://stork.eu", portName = "SPDocumentServicePort", serviceName = "SPDocumentService")
public class SPDocumentServiceImpl implements SPDocumentService {

	static String COUNTRY;
	private DatabaseConnector conn;
	private Properties props = new Properties();
	private static final Logger LOG = Logger.getLogger(DocumentServiceImpl.class.getName());
	
	@Override
	public String addSPSignDocument(byte[] document, String SpId, String mimeType, String receiverCert)
	{
		String returnMessage = "";
		if (document != null)
		{			
			try 
			{
				LOG.trace("Adding temp document starting, document size: " + Integer.toString(document.length)
						+ ", SP Id: " + SpId + ", mime type: " + mimeType + " receiver cert: " + receiverCert);
				props.load(DatabaseConnectorMySQLImpl.class.getResourceAsStream("docservice.properties"));
				COUNTRY = props.getProperty("peps.country");				
				
				conn = new DatabaseConnectorMySQLImpl(props.getProperty("sql.user"), props.getProperty("sql.password"), 
						props.getProperty("sql.server"), props.getProperty("sql.database"));

				TempDocumentModel doc = new TempDocumentModel();
				doc.setDocid(UUID.randomUUID().toString());
				doc.setDocument(document);
				doc.setSpid(SpId);
				doc.setMimetype(mimeType);
				doc.setReicevercert(receiverCert);
				if (conn.addTempDocument(doc))
				{
					LOG.trace("Document added successfully. DocID: " + doc.getDocid());
					returnMessage = doc.getDocid();
				}
				else
				{
					LOG.warn("Could not add document.");
					throw new WebServiceException("Could not add document.");
				}
			}
			catch (ModelException e)
			{
				LOG.error("Invalid model in input", e);
				e.printStackTrace();
				throw new WebServiceException("Invalid input.", e);
			}
			catch (Exception e)
			{
				LOG.error("Exception in SP addDocument.", e);
				e.printStackTrace();
				throw new WebServiceException("Upload Failed");
			}
			LOG.trace("Add document ending, return message: " + returnMessage);
			return returnMessage;
		}
		else
			throw new WebServiceException("No document to upload.");
	}

	@Override
	public byte[] getSPDocument(String docId, String spId) 
	{
		try
		{
			if (docId != null && !docId.isEmpty())
			{			
				LOG.trace("Getting temp document from database for docId: " + docId);
				docId = XmlHelper.StripDocId(docId);
				props.load(DatabaseConnectorMySQLImpl.class.getResourceAsStream("docservice.properties"));
				conn = new DatabaseConnectorMySQLImpl(props.getProperty("sql.user"), props.getProperty("sql.password"), 
						props.getProperty("sql.server"), props.getProperty("sql.database"));
				TempDocumentModel doc = conn.getTempDocument(docId);
				if (doc != null)
				{
					LOG.trace("Document found.");
					if (doc.getSpid().equals(spId))
					{
						LOG.trace("Getting document from database ending. Document supplied.");
						return doc.getDocument();
					}
					else
					{
						LOG.warn("Document SP ID of " + doc.getSpid() + " does not match sent SP ID of " + spId);
						throw new WebServiceException("Incorrect SP ID."); 
					}
				}
				else
				{
					LOG.warn("Document is null");
					throw new WebServiceException("Document is null.");
				}
			}
			else
			{
				LOG.warn("Document id is null or empty.");
				throw new WebServiceException("Document Id is null");
			}			
		}
		catch (Exception e)
		{
			LOG.error("Exception in SP getDocument.", e);
			e.printStackTrace();
			throw new WebServiceException("Download Failed", e);
		}
	}
}