//$Id

package com.action;

//java imports
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.DispatchAction;
import java.io.*;
import java.util.*;

//
import com.util.ZohoUtil;

/**
 * DocumentsMgr is used in handling the documents related requests.
 * This class extends org.apache.struts.actions.DispatchAction. Documents related request from the clients are hanlded in this class. Requests are processed and the proper responses will be sent back to the clients.
 *
 * @version 1.0
 * @see org.apache.struts.actions.DispatchAction
 * @see com.ea.zoho.server.util.ZohoUtil
 */
public class DocumentsMgr extends DispatchAction 
{
    
    /**
     * Performs the cancel-sharing operation of a shared document for the given emailId.
     * This method is called through AJAX request. This method is called while the cancel-sharing operation is performed at the client end. Following parameters(given with the definitions) are fetched from the HttpServletRequest object, <br>
     *        apiTicket - User Ticket associated with the zoho service <br>
     *        type - type of the document(document/workbook/presentation) <br>
     *        docId - Document Id of the document on which this operation needs to be performed<br>
     *        mailId - EMail Id for which the sharing needs to be cancelled <br>
     *        access - current access permission(readOnly/readWrite) for this email id<br> <br>
     * Performs the cancel-sharing operation using the {@link com.ea.zoho.server.util.ZohoUtil#cancelShare}.Sends back the response to the client.
     *
     * @return null
     */
    public ActionForward revertSharing(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest req,
                                 HttpServletResponse res)
    {
        String apiTicket = req.getParameter("apiTicket");
        String docType = req.getParameter("type");
        String docId = req.getParameter("docId");
        String mailId = req.getParameter("mailId");
        String access = req.getParameter("access");
        System.out.println("DocumentsMgr:revertSharing:"+
           "apiTicket:"+apiTicket+"***** docType:"+docType+"******"+
           "docId:"+docId+"***** mailId:"+mailId+"***** access:"+access+"***");    
        try
        {
            String response = "";
            //Returns mailId, if the cancelling is not successfull
            String resp = ZohoUtil.cancelShare(docId,docType,
                             apiTicket,mailId);
            String result = "success";
            //if failure, checks with the response
            if(resp.equals("mailId"))
            {
                 result = "failure";    
            }
            response = "{\"docId\":\""+docId+"\",\"mailId\":\""+mailId
                       +"\",\"access\":\""+access+"\",\"result\":\""+result+"\"}";
            System.out.println("DocumentsMgr:revertSharing:response:"+response);    
            PrintWriter out = res.getWriter();
            StringBuffer sb = new StringBuffer();
            out = res.getWriter();
            sb.append(response);
            res.setContentType("text/xml");
            res.setContentLength(sb.length());
            out.println(sb);
        }
        catch(Exception e)
        {
            System.out.println("DocumentsMgr:cancelSharing:"+
                    "apiTicket:"+apiTicket+"***** docType:"+docType+"******"+
                    "docId:"+docId+"***** mailId:"+mailId+"***** access:"+access+"***");    
            e.printStackTrace();    
        }
        return null;
    }
    
    /**
     * Shares a document to a list of emailIds with appropriate access permission.
     * This method is called through AJAX request. This method is called while sharing a document to a list of emailIds at client end.Following parameters are fetched from the HttpServletRequest object,<br>
     *       apiTicket - User ticket associated with zoho service <br>
     *       readOnlyUsers - list of emailIds with read-only permission<br>
     *       edit - list of emailIds with read-write permission<br>
     *       type - type of the document<br>
     *       docId - Document Id of the document to be shared <br>
     *       userName - Name of the user who shares the document<br> <br>
     * If the docType is document/presentation, shares the document to the emailIds using {@link com.ea.zoho.server.util.ZohoUtil#shareWriterShowDoc}.Else if the docType is workbook, shares the document using {@link com.ea.zoho.server.util.zohoconnectUtil#shareSheetDoc}. Sends back the response to the client. 
     *
     * @return null
     */
    public ActionForward shareDocument(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest req,
                                 HttpServletResponse res)
    {
        String ticketId = req.getParameter("apiTicket");
        String readOnlyUsers = req.getParameter("readOnly");
        String editUsers = req.getParameter("edit");
        String docType = req.getParameter("type");
        String docId = req.getParameter("docId");
        String userName = req.getParameter("userName");
        System.out.println("DocumentsMgr:shareDocument::"+
            "ticketId*****"+ticketId+"***readOnlyUsers:"+readOnlyUsers+
            "*** editUsers:"+editUsers+"*****docType:"+docType+"**"+
            "docId::"+docId+"********userName:"+userName+"***");
        try
        {
            String response = "";
            if(docType.equals("document") || docType.equals("presentation"))
            {
                response = ZohoUtil.
                    shareWriterShowDoc(ticketId,readOnlyUsers,
                       editUsers,docId,userName,docType);
            }
            else if(docType.equals("workbook"))
            {
                response = ZohoUtil.
                    shareSheetDoc(ticketId,readOnlyUsers,editUsers,docId,userName);
            }
            
            PrintWriter out = res.getWriter();
            StringBuffer sb = new StringBuffer();
            out = res.getWriter();
            sb.append(response);
            res.setContentType("text/xml");
            res.setContentLength(sb.length());
            out.println(sb);
        }
        catch(Exception e)
        {
            System.out.println("DocumentsMgr:shareDocument::"+
                    "ticketId*****"+ticketId+"***readOnlyUsers:"+readOnlyUsers+
                    "*** editUsers:"+editUsers+"*****docType:"+docType+"**"+
                    "docId::"+docId+"********");
            e.printStackTrace();    
        }
        return null;
    }
    
    /**
     * Fetches the complete shared documents list for an user from zoho services(Writer,Sheet and Show).
     * This method is called through AJAX request. This method is called at the time of listing shared documents list in Documents view. Fetches the apiTicket(user ticket associated with zoho service) from the HttpServletRequest object. Gets the shared documents list using {@link com.ea.zoho.server.util.ZohoUtil#getSharedDoc} and returns the same to the client.
     *
     * @return null
     */
    public ActionForward getSharedDocsList(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest req,
                                 HttpServletResponse res)
    {
        String ticketId = req.getParameter("apiTicket");
        System.out.println("DocumentsMgr:getSharedDocsList:"+
           "ticketId:::"+ticketId+"***");
        try
        {
            PrintWriter out = res.getWriter();
            StringBuffer sb = new StringBuffer();
            out = res.getWriter();
            String response = ZohoUtil.getSharedDoc(ticketId);
            sb.append(response);
            res.setContentType("text/xml");
            res.setContentLength(sb.length());
            out.println(sb);
        }
        catch(Exception e)
        {
            System.out.println("DocumentsMgr:getSharedDocsList:"+
                    "ticketId:::"+ticketId+"***");
            e.printStackTrace();    
        }
        return null;
    }
  
    /**
     * Forwards the request to render the documents view at the client end.
     *
     * @return forwards the request to render the documents view
     */
    public ActionForward forwardToDocumentsPage(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest req,
                                 HttpServletResponse res)
    {
        //System.out.println("DocumentsMgr:: "+
        //        "Inside forwardToDocumentsPage**");    
        return mapping.findForward("showDocsList");
    }

    /**
     * Fetches the complete private documents of an user from zoho services(Writer,Sheet and Show).
     * This method is called through AJAX request. This method is called while opening the Documents view. Fetches the apiTicket(user ticket associated with zoho service) from the HttpServletRequest object. Fetches the documents from zoho services using {@link com.ea.zoho.server.util.ZohoUtil#getCompleteDocs}.Sends back the response to the client in XML format.
     *
     * @return null
     */
    public ActionForward getCompleteDocsList(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest req,
                                 HttpServletResponse res)
    {
        PrintWriter out = null;
        String response = "";
        String startFrom = req.getParameter("start-from");
        String limit = req.getParameter("limit");
        String apiTicket = req.getParameter("apiTicket");
        if(apiTicket==null)
        {
            apiTicket=req.getSession().getAttribute("apiTicket").toString();
        }    
        try
        {
            
            //String apiTicket = "bd9161f05b28f1f9b2a9c2b2cbb57163";
            StringBuffer sb = new StringBuffer();
            out = res.getWriter();
            response = ZohoUtil.getCompleteDocs(
                    apiTicket,startFrom,limit);
            sb.append(response);
            res.setContentType("text/xml");
            res.setContentLength(sb.length());
            out.println(sb);
        }
        catch(Exception e)
        {
            System.out.println("DocumentsMgr:: getCompleteDocsList***"+
                "Start-From::"+startFrom+"** Limit:"+limit
                +"* apiTicket:"+apiTicket+"*");
            e.printStackTrace();    
        }
        return null;
    }

    /**
     * Default method of this class.
     * This method is called at the time of displaying the Documents view(i.e. document.do). Forwards the request to render the documents view at the client end.
     *
     * @return forwards the request to render the documents view
     */
    public ActionForward unspecified(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest req,
                                 HttpServletResponse res)
    {
        //System.out.println("DocumentsMgr::unspecified");    
        return forwardToDocumentsPage(mapping,form,req,res);
    }

    /**
     * Opens the editor page for the existing document.
     * Fetches the following parameters from HttpServletRequest object,<br>
     *       apiTicket - User ticket associated with zoho service<br>
     *       docId - Document Id of the document to be opened<br>
     *       docType - type of the document(document/workbook/presentation)<br>
     *       docName - document name<br><br>
     * Fetches the corresponding editor URL using {@link com.ea.zoho.server.util.ZohoUtil#getEditorURL} and forwards the request to render the editor view at client end.
     *
     * @return forwards the request to render the editor view at client end
     */
    public ActionForward getEditorPage( ActionMapping mapping,
                                   ActionForm form,
                                HttpServletRequest req,
                                HttpServletResponse res)
    {
        String apiTicket = req.getParameter("apiTicket");
        //String apiTicket = "bd9161f05b28f1f9b2a9c2b2cbb57163";
        String docId = req.getParameter("docId");
        String docType = req.getParameter("docType");
        String docName = req.getParameter("docName");
        System.out.println("DocumentsMgr::getEditorPage**"
                +"DocID::"+docId+"****  DocType::"
                +docType+"** DocName:"+docName+"* apiTicket:"+apiTicket);
        String editorURL = ZohoUtil.getEditorURL(docType,docId,
                              docName,true,apiTicket);
        req.setAttribute("editorURL",editorURL);
        return mapping.findForward("editorPage");
    }

    /**
     * Returns the sheet preview URL for a Sheet document.
     * This method is called through AJAX call.This method is called while preview is opening for a workbook at client end. Fetches the following parameters from HttpServletRequest object,<br>
     *       apiTicket - User ticket associated with zoho service<br>
     *       docId - Document Id of the document to be opened<br>
     *       docType - type of the document(document/workbook/presentation)<br>
     *       docName - document name <br><br>
     * Fetches the corresponding URL using {@link com.ea.zoho.server.util.ZohoUtil#getSheetPreviewURL}.And sends the fetched URL to the client.
     *
     * @return null
     */
    public ActionForward getSheetPreview( ActionMapping mapping,
                                   ActionForm form,
                                HttpServletRequest req,
                                HttpServletResponse res)
    {
        String apiTicket = req.getParameter("apiTicket");
        //String apiTicket = "bd9161f05b28f1f9b2a9c2b2cbb57163";
        String docId = req.getParameter("docId");
        String docType = req.getParameter("docType");
        String docName = req.getParameter("docName");
        try
        {
            StringBuffer sb = new StringBuffer();
            PrintWriter out = res.getWriter();
            String response = ZohoUtil.getSheetPreviewURL(docType,
                    docId,docName,apiTicket);
            sb.append(response);
            //res.setContentType("text/xml");
            res.setContentLength(sb.length());
            out.println(sb);
            return null;
        }
        catch(Exception e)
        {
            System.out.println("DocumentsMgr::getSheetPreview**"
                +"DocID::"+docId+"****  DocType::"
                +docType+"** DocName:"+docName+"* apiTicekt:"+apiTicket);
            e.printStackTrace();    
        }
        return null;
    }

    /**
     * Gets a document's content from zoho service.
     * This method is called through AJAX call. Fetches the following parameters from HttpServletRequest object,<br>
     *       apiTicket - User ticket associated with zoho service<br>
     *       docId - Document Id of the document to be opened<br>
     *       docType - type of the document(document/workbook/presentation)<br>
     *       docName - document name <br><br>
     * Fetches the document content from zoho service using {@link com.ea.zoho.server.util.ZohoUtil#getDocumentContent}.Sends back the response to the client.
     *
     * @return null
     */
    public ActionForward getDocContent( ActionMapping mapping,
                                   ActionForm form,
                                HttpServletRequest req,
                                HttpServletResponse res)
    {
        String apiTicket = req.getParameter("apiTicket");
        //String apiTicket = "bd9161f05b28f1f9b2a9c2b2cbb57163";
        String docId = req.getParameter("docId");
        String docType = req.getParameter("docType");
        String docName = req.getParameter("docName");
        try
        {
            StringBuffer sb = new StringBuffer();
            PrintWriter out = res.getWriter();
            String response = ZohoUtil.getDocumentContent(docType,
                    docId,docName,apiTicket);
            sb.append(response);
            res.setContentType("text/xml");
            res.setContentLength(sb.length());
            out.println(sb);
            return null;
        }
        catch(Exception e)
        {
            System.out.println("DocumentsMgr::getDocContent**"
                +"DocID::"+docId+"****  DocType::"
                +docType+"** DocName:"+docName+"* apiTicket:"+apiTicket);
            e.printStackTrace();    
        }
        return null;
    }

    /**
     * Opens the editor page for the new document.
     * Fetches the following parameters from HttpServletRequest object,<br>
     *       apiTicket - User ticket associated with zoho service<br>
     *       docType - type of the document(document/workbook/presentation)<br>
     * Fetches the corresponding editor URL using {@link com.ea.zoho.server.util.ZohoUtil#getNewDocURL} and forwards the request to render the editor view at client end.
     *
     * @return forwards the request to render the editor view at client end
     */
    public ActionForward getNewDoc( ActionMapping mapping,
                                   ActionForm form,
                                HttpServletRequest req,
                                HttpServletResponse res)
    {
        String apiTicket = req.getParameter("apiTicket");
        //String apiTicket = "bd9161f05b28f1f9b2a9c2b2cbb57163";
        String docType = req.getParameter("docType");
        System.out.println("DocumentsMgr:: getNewDoc::"+
                "DocumentType::"+docType+"* apiTicket:"+apiTicket+"*");
        String docURL = ZohoUtil.getNewDocURL(docType,apiTicket);
        req.setAttribute("editorURL",docURL);
        return mapping.findForward("editorPage");
    }

    /**
     * Deletes the documents from zoho services(Writer,Sheet and Show).
     * This method is called through AJAX request. This method is called while deleting documents from the Documents view. Fetches the apiTicket(user ticket associated with zoho service) and list of documents(with comma separation) to be deleted from the HttpServletRequest object. Deletes all the documents one-by-one using {@link com.ea.zoho.server.util.ZohoUtil#deleteDoc}.Sends back the response to the client in JSON format.
     *
     * @return null
     */
    public ActionForward deleteDoc( ActionMapping mapping,
                                   ActionForm form,
                                HttpServletRequest req,
                                HttpServletResponse res)
    {
        String apiTicket = req.getParameter("apiTicket");
        //String apiTicket = "bd9161f05b28f1f9b2a9c2b2cbb57163";
        String docParams = req.getParameter("docParams");
        try
        {
            StringBuffer response = new StringBuffer();
            response.append("[");
            StringTokenizer st = new StringTokenizer(docParams,",");
            while (st.hasMoreTokens())
            {
                String param = st.nextToken();
                String[] strArr = param.split("_");
                String docType = strArr[1];
                String docId = strArr[0];
                //System.out.println("DocumentsMgr:: deleteDoc:"+
                //     "DocId::"+docId+"*******DocType::"+docType
                //     +"* apiTicket:"+apiTicket+"*");
                boolean isDeleted=ZohoUtil.deleteDoc(docId,docType,apiTicket);
                if(isDeleted)
                {
                     response.append("{docId:\""+docId+"\",result:\"success\",docType:\""+docType+"\"},");
                }
                else
                {
                     response.append("{docId:\""+docId+"\",result:\"failure\",docType:\""+docType+"\"},");
                }
            }
            String stringResp = response.substring(0);
            if(stringResp.endsWith(","))
            {
                stringResp = stringResp.substring(0,(stringResp.length()-1));
            }
            stringResp = stringResp+"]";
            //System.out.println("DocumentsMgr:deleteDoc:"+
            //    "apiTicket:"+apiTicket+"**docParams:"+docParams+"* result:"+
            //    stringResp+"**********");    
            PrintWriter out = res.getWriter();
            StringBuffer sb = new StringBuffer();
            sb.append(stringResp);
            res.setContentLength(sb.length());
            out.println(sb);
            return null;
        }
        catch(Exception e)
        {
            System.out.println("DocumentsMgr:deleteDoc:"+
              "apiTicket:::"+apiTicket+"**** docParams::"+docParams+"**");
            e.printStackTrace();    
        }
        return null;
    }

    /**
     * Gets the private documents count of an user in a zoho service(Writer/Sheet/Show).
     * This method is called through AJAX request. Fetches the following parameters from HttpServletRequest object,<br>
     *       apiTicket - User ticket associated with zoho service<br>
     *       docType - type of the document(document/workbook/presentation)<br>
     * Gets the document count using {@link com.ea.zoho.server.util.ZohoUtil#getDocCountResponse} and sends back the response to the client.
     *
     * @return null
     */
    public ActionForward getDocCount( ActionMapping mapping,
                                   ActionForm form,
                                HttpServletRequest req,
                                HttpServletResponse res)
    {
        String apiTicket = req.getParameter("apiTicket");
        String docType = req.getParameter("docType");
        try
        {
            String response = 
                ZohoUtil.getDocCountResponse(docType,apiTicket);
            PrintWriter out = res.getWriter();
            StringBuffer sb = new StringBuffer();
            sb.append(response);
            res.setContentType("text/xml");
            res.setContentLength(sb.length());
            out.println(sb);
        }
        catch(Exception e)
        {
            System.out.println("DocumentsMgr:getDocCount:"+
               "apiTicket:"+apiTicket+"****** docType:"+docType+"*");
            e.printStackTrace();    
        }
        return null;
    }
}
