package oracle.fusion.pts.restService;


import com.oracle.xmlns.apps.crmcommon.activities.activitymanagementservice.Activity;
import com.oracle.xmlns.apps.crmcommon.activities.activitymanagementservice.ObjectFactory;

import com.oracle.xmlns.apps.crmcommon.salesparties.accountservice.Account;

import java.io.InputStream;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

import javax.xml.bind.JAXBException;


import oracle.demo.pts.fusionproxy.activity.ServiceException;
import oracle.demo.pts.fusionservices.FusionActivityService;

import oracle.fusion.pts.restService.exceptions.FusionGenericException;
import oracle.fusion.pts.restService.types.DMLOperation;
import oracle.fusion.pts.restService.types.RESTAccountList;
import oracle.fusion.pts.restService.types.RESTActivityList;
import oracle.fusion.pts.restService.types.RESTOpportunityList;
import oracle.fusion.pts.restService.utils.RESTfulFusionService;


@Path("/activity")
public class RESTfulActivityService extends RESTfulFusionService {
    FusionActivityService objectService = new FusionActivityService();
    String fusionEndpointName = "fusionCRMActivityEndpoint";
    ObjectFactory intObjFactory = new ObjectFactory();


    /**
     * Handles CRUD for Activity Service
     *
     * @param pHttpHeaders
     * @param activityList
     * @param operation
     * @return
     */
    private RESTActivityList doDMLActivtyXML(HttpHeaders pHttpHeaders,
                                             RESTActivityList activityList,
                                             DMLOperation operation) {
        // Initialise Proxy endpoint
        processRESTServiceHeaders(pHttpHeaders);
        objectService.initialiseConnection(this.getFusionJWTToken(),
                                                   getFusionUsername(),
                                                   getFusionPassword(),
                                                   getFusionEndpointURL(fusionEndpointName),
                                                   this.getFetchSize(),
                                                   this.getFetchStart());

        Activity activity;
        if (activityList.getActivityList() == null) {
            throw new WebApplicationException(Response.Status.BAD_REQUEST);
        }
        // Extract out the opportunity, assume its the first one
        activity = activityList.getActivityList().iterator().next();
        Activity result = null;

        try {
            if (operation == DMLOperation.CREATE)
                result =
                        objectService.getService().createActivity(activity);
            else if (operation == DMLOperation.MERGE)
                // must be UPDATE
                result =
                        objectService.getService().updateActivity(activity);


            else if (operation == DMLOperation.DELETE) {
                objectService.getService().deleteActivity(activity);

            } else
                throw new WebApplicationException(Response.Status.BAD_REQUEST);

        } catch (ServiceException e) {
            throw new FusionGenericException(e.getLocalizedMessage());

        }
        // Wrap it up so JAX-RS is happy
        ArrayList<Activity> aoo = new ArrayList<Activity>();
        aoo.add((Activity)result);
        RESTActivityList rol2 = new RESTActivityList();
        rol2.setActivityList(aoo);
        return rol2;

    }

    @GET
    @Path("{activityid}")
    @Produces( { "application/xml", "application/json" })
    public RESTActivityList getActivity(@Context
        HttpHeaders pHttpHeaders, @PathParam("activityid")
        Long pActivityId, @QueryParam("attributes")
        String pAttributes) throws JAXBException {
        // Init
        processRESTServiceHeaders(pHttpHeaders);
        objectService.initialiseConnection(this.getFusionJWTToken(),
                                                   this.getFusionUsername(),
                                                   this.getFusionPassword(),
                                                   this.getFusionEndpointURL(fusionEndpointName),
                                                   this.getFetchSize(),
                                                   this.getFetchStart());
        this.logMessage("getActivity called for " + pActivityId);
        List<Activity> result = null;
        try {
            String seperator =
                objectService.getDefaultMinorQuerySeperator();
            result =
                    objectService.find("", pAttributes, "ActivityId" +
                                                       seperator + "=" +
                                                       seperator + pActivityId,
                                                       "");


        } catch (NumberFormatException e) {
            throw new FusionGenericException("NumberFormatException, received " +
                                             pActivityId + " for activityid");
        } catch (com.sun.xml.ws.client.ClientTransportAccessException ctae) {
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        } catch (Exception e) {


            logMessage("exception @ getActivity");
            e.printStackTrace();
            throw new FusionGenericException(e.getLocalizedMessage());

        }
        if (result.size() < 1) {
            // No Activity found
            logMessage("No Activity " + pActivityId + " found");
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        logMessage("Result of getActivity " + result.get(0).getActivityId());
        // Wrap it up so JAX-RS is happy
        RESTActivityList li2 = new RESTActivityList();
        li2.setActivityList(result);
        return li2;
    }
    
    public RESTActivityList getActivity4Opportunity(HttpHeaders pHttpHeaders,
                                                    Long pOpportunityId,
                                                    String pAttributes) {
        logMessage("getActivity4Opportunity for " + pOpportunityId);
        processRESTServiceHeaders(pHttpHeaders);
        objectService.initialiseConnection(this.getFusionJWTToken(),
                                                   getFusionUsername(),
                                                   getFusionPassword(),
                                                   getFusionEndpointURL(fusionEndpointName),
                                                   this.getFetchSize(),
                                                   this.getFetchStart());


        List<Activity> activities = null;

        String pSOAPMessageString =
            "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
            "xmlns:typ=\"http://xmlns.oracle.com/apps/crmCommon/activities/activityManagementService/types/\" " +
            "xmlns:typ1=\"http://xmlns.oracle.com/adf/svc/types/\">\n" +
            "   <soapenv:Header/>\n" +
            "   <soapenv:Body>\n" +
            "      <typ:findActivity>\n" +
            "         <typ:findCriteria>\n" +
            "            <typ1:filter>\n" +
            "               <typ1:group>\n" +
            "                  <typ1:upperCaseCompare>true</typ1:upperCaseCompare>\n" +
            "                  <typ1:item>\n" +
            "                     <typ1:upperCaseCompare>true</typ1:upperCaseCompare>\n" +
            "                     <typ1:attribute>OpportunityId</typ1:attribute>\n" +
            "                     <typ1:operator>=</typ1:operator>\n" +
            "                     <typ1:value>" + pOpportunityId.toString() + "</typ1:value>\n" +
            "                  </typ1:item>\n" +
            "               </typ1:group>\n" +
            "            </typ1:filter>\n" +
            "            <typ1:excludeAttribute/>\n" +
            "            <typ1:fetchStart>0</typ1:fetchStart>\n" +
            "            <typ1:fetchSize>500</typ1:fetchSize>\n" +
            "            <typ1:sortOrder>\n" +
            "               <typ1:sortAttribute>\n" +
            "                  <typ1:name>LastUpdateDate</typ1:name>\n" +
            "                  <typ1:descending>true</typ1:descending>\n" +
            "               </typ1:sortAttribute>\n" +
            "            </typ1:sortOrder>\n" +
            "         </typ:findCriteria>\n" +
            "         <typ:findControl>\n" +
            "            <typ1:retrieveAllTranslations>false</typ1:retrieveAllTranslations>\n" +
            "         </typ:findControl>\n" +
            "      </typ:findActivity>\n" +
            "   </soapenv:Body>\n" +
            "</soapenv:Envelope>";


        try {
            activities = objectService.find

                    (pSOAPMessageString, pAttributes, null, null);
        } catch (com.sun.xml.ws.client.ClientTransportAccessException ctae) {
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        } catch (Exception e) {
            logMessage("exception @ findActivity");
            e.printStackTrace();
            throw new FusionGenericException(e.getLocalizedMessage());

        }
        logMessage("Number of Activities found " + activities.size());
        RESTActivityList li2 = new RESTActivityList();
        li2.setActivityList(activities);
        return li2;
    }


    @GET
    @Produces( { "application/xml", "application/json" })
    public RESTActivityList find(@Context
        HttpHeaders pHttpHeaders, @QueryParam("attributes")
        String pAttributes, @QueryParam("query")
        String pQuery, @QueryParam("conjunction")
        String pConjunction, InputStream pInputStream) throws JAXBException {
        
        String xmlQuery=convertStreamToString(pInputStream);                                                     
        // Initialise the connections
        processRESTServiceHeaders(pHttpHeaders);
        objectService.initialiseConnection(this.getFusionJWTToken(), this.getFusionUsername(), this.getFusionPassword(), this.getFusionEndpointURL(fusionEndpointName), this.getFetchSize(), this.getFetchStart());
        
        List<Activity> result = null;
        try {
            result=objectService.find(xmlQuery,pAttributes,pQuery,pConjunction);
        } 
        catch (com.sun.xml.ws.client.ClientTransportAccessException ctae) {
            throw new WebApplicationException(Response.Status.UNAUTHORIZED);
        }
        catch (Exception e) {
            logMessage("exception @ findActivity");
            e.printStackTrace();
            throw new FusionGenericException(e.getLocalizedMessage());    
        }
        logMessage("Number of Activities found " + result.size());
        
        RESTActivityList ro2=new RESTActivityList();
        ro2.setActivityList(result);

        
        return ro2;
    }

    @POST
    @Path("/xmlquery")
    @Produces({"application/xml", "application/json"})
    public RESTActivityList findXMLQuery(@Context HttpHeaders pHttpHeaders,
                               InputStream pInputStream) throws JAXBException {
        return (find(pHttpHeaders,"","","",pInputStream));    
    }

   
}
