package gov.epa.state.sample.client;

import gov.epa.cdx.axis.v10.client.NodeRequestor;
import gov.epa.cdx.commons.log.LogFactory;
import gov.epa.cdx.commons.log.LogInterface;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;

/**

 * User: David Dundua
 * Date: May 29, 2003
 * Time: 11:17:38 AM
 */
public class Client
{
    private static LogInterface log = LogFactory.getLog(Client.class.getName());
    private static String TARGET_URL;

    static
    {
        Client.loadProperties();
    }

    private static URL validateAndReturnURL(String URLString)
    {
        URL url = null;
        try
        {
            url = new URL(URLString);
        }
        catch (MalformedURLException ex)
        {
            new Exception(URLString + " is malformed URL. Fatal exception.");
        }

        return url;
    }

    public static void main(String[] args)
    {
        String USERNAME = "cdx";
        String PASSWORD = "test";
        String DATAFLOWTYPE = "FRS";
        String DOCUMENTNAME = "testSubmit.xml";
        String DOCUMENTTYPE = "XML";
        String SERVICEREQUEST ="GetFacilityByName";
        String [] SERVICEPARAMETERVALUES = {"NE", "BECHIUS FARM"};
        String SERVICETYPE = "Query";
        String STATUSNOTIFYMSG = "The transaction has been completed.";
        String STATUS = "COMPLETED";
        
        NodeRequestor requestor = null;

        try
        {
            //please note we are going over https
            URL url = validateAndReturnURL(TARGET_URL);
            log.debug("[client]: Using URL " + url.toString() );
            requestor = new NodeRequestor(url);

            //first lets ping
            String response = requestor.nodePing("hello");
            log.debug("[nodePing]: Recieved response " + response );

            String token = requestor.authenticate(USERNAME, PASSWORD);
            log.debug("[authenticate]: Recieved security token " + token );

            byte[] byteArray = {111, 111};
            String transactionId =
                    requestor.submit(token, "", DATAFLOWTYPE, DOCUMENTNAME, DOCUMENTTYPE, byteArray);
            log.debug("[submit]: Recieved transactionId from submit " + transactionId );

            //check status of submited document
            String status =
                    requestor.getStatus(token, transactionId);
            log.debug("[getStatus]: Status of transaction " + transactionId + " is " + status );

            //download the document that was just sumitted
            byte[] documentConent = requestor.download(token, transactionId, DATAFLOWTYPE, DOCUMENTNAME, DOCUMENTTYPE);
            log.debug("[download]: Recieved document of size  " + documentConent.length + " bytes." );
             long startTime = System.currentTimeMillis();
            //lets perform query agains FRS
            byte[] queryResultContent =
                    requestor.query(token, SERVICEREQUEST, new BigInteger("0"), new BigInteger("0"), SERVICEPARAMETERVALUES);
            long took = System.currentTimeMillis() - startTime;
            log.debug("The query took " + took + "ms.");
            log.debug("[query]: Begin:" );
            String output = new String (queryResultContent);
            log.debug(output);
            log.debug("[query]: End");

            //perform solicit
            String solicitTransactionId =
                    requestor.solicit(token, null, SERVICEREQUEST,  SERVICEPARAMETERVALUES);
            log.debug("[solicit]: Recieved transactionId from solicit " + solicitTransactionId );

            //status notify
            String statusNotifyTransaction =
            		requestor.statusNotify(token, transactionId, STATUS, STATUSNOTIFYMSG.getBytes() );
            log.debug("[statusNotify]: Recieved transactionId from status notify " + statusNotifyTransaction );
            
            //get list services
            String [] services =
                    requestor.getServices(token, SERVICETYPE);
            log.debug("[getServices]: List of supported services: ");
            for (int counter = 0; counter < services.length; counter++) {
                String service = services[counter];
                log.debug(counter + " " + service);
            }
            log.debug("[getServices]: End of List of supported services.");


        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

    }


    private static void loadProperties()
    {
        String fileName = "Locator.properties";
        String DEFAULT_URL = "https://epacdxnode.net/cdx/services/NetworkNodePortType_V10";
        Properties prop = new Properties();
        try
        {
            prop.load(new FileInputStream(fileName));
        }
        catch (FileNotFoundException ex)
        {
            log.info("File "+ fileName + " not found. Make sure you place that file in the same directory");
            log.info("Using default URL: " + DEFAULT_URL);

        }
        catch (IOException exc)
        {
            log.info("Error reading properties file " +fileName + "check to make sure contents are properly formed. ");
            log.info("Using default URL: " + DEFAULT_URL);
        }

        TARGET_URL = prop.getProperty("CLIENT_TARGET_URL", DEFAULT_URL);
    }
}
