
//$Id: SendMeetingLink.java,v 1.1 2008/06/18 12:29:33 ahmed Exp $




//
package com.util;

//
import java.util.TimerTask;
import java.util.Timer;
import java.util.Vector;
    
/**
 *
 */
public class SendMeetingLink extends TimerTask 
{
    //
    private MailUtil mu = new MailUtil();

    
    //
    private String response = "";

    //
    private String participantsList = "";

    //
    private String topic = "";

    //
    private String ddate = "";

    //
    private String ttime = "";

    //
    private String agenda = "";

    //
    private String presenter = "";

    //
    private String meetingKey = "";

    //
    private String thisUser = "";

    //
    private String timezone = "";
    //
    private String path = "";

    /**
     *
     */
    public SendMeetingLink( String response , String presenter , 
            String participants , String topic , String time , 
            String agenda , String timeZone , String userName,
            String meetingKey,String path)
    {
        this.response = response;
        this.presenter = presenter;
        this.participantsList = participants;
        this.topic = topic ; 
        this.ttime = time;
        this.agenda = agenda;
        this.thisUser = userName;
        this.meetingKey = meetingKey;
        this.timezone = timeZone;
        this. path= path;
        Timer t = new Timer();
        t.schedule(this,0l);
    }

    //
    public void run()
    {
        try
        {
            String content = "";
            String subject = "ZohoConnect Meeting Invite: "+topic;
            String contentType = "text/html";
            String sender = "ZohoConnect";
            //Invite message by default
            String inviteMessage = " has invited you for a virtual meeting"; 

            //On creating a meeting
            if(response.indexOf("/api/private/json/meetings/createMeeting") != -1)
            {
                setMeetingKey();
                if(meetingKey == null || meetingKey.trim().equals(""))
                {
                    sop("Received an invalid meetingKey in the response:"
                            +response+"*** meetingKey:"+meetingKey,"normal");
                    return;
                }

                //Presenter
                content = getContent( presenter , "presenter" , inviteMessage);
                try
                {
                    String rponse = mu.despatch(subject , presenter , 
                            content,contentType,sender);
                }
                catch(Exception ex)
                {
                    sop("Exception while sending meeting mail to the presenter:"
                            +presenter+"*******Topic:"+topic,"normal");
                }
            }
            //Checking the response of invite before sending e-mails
            else if(response.indexOf("/api/private/json/meetings/inviteParticipant") != -1)
            {
                //If response doesnot contain "result" tag or "Participant Invited", 
                //returning without performing any operations.
                if(response.indexOf("\"result\"") == -1 || 
                    response.indexOf("\"Participant Invited\"") == -1)
                {
                    return;
                }
            }
            //Checking the response of edit meeting
            else if(response.indexOf("/api/private/json/meetings/updateMeeting") != -1)
            {
                String topicDelm = ":::123_existing_topic_123:::";
                String timeDelm = ":::existing_Time:::";

                //Topic parsing
                String currTopic = (topic.split(topicDelm))[0];
                String extTopic = (topic.split(topicDelm))[1];
                topic = currTopic;

                //Time parsing
                String currTime = (ttime.split(timeDelm))[0];
                String extTime = (ttime.split(timeDelm))[1];
                ttime = currTime;
                //fitering out the month and date
                extTime = (extTime.split(","))[0];

                String modSub = extTopic+" created on "+extTime+" - modified";
                String subjectOnEdit = 
                    "ZohoConnect Meeting - Meeting Updated: "+modSub;
                String updateMessage = " has updated the virtual meeting, "+modSub;

                //Handling Presenter part
                String presenterDel = ":::existing_Presenter:::";
                int lnOfpd = presenterDel.length();
                int indxOfpd = presenter.indexOf(presenterDel);
                String currPresenter = presenter.substring(0,indxOfpd);
                String extPresenter = presenter.substring((indxOfpd+lnOfpd));
                String presenterSub = "";
                //Setting presenter value
                presenter = currPresenter;
                //Means the presenter is changed - Send invite mail
                if(!currPresenter.equals(extPresenter))
                {
                     content = getContent(currPresenter,"presenter",inviteMessage);
                     presenterSub = "ZohoConnect Meeting Invite: "+topic;
                }
                //Presenter not changed - Send update mail
                else
                {
                     content = getContent(currPresenter,"presenter",updateMessage);
                     presenterSub = subjectOnEdit;
                }
                try
                {
                    String respp = mu.despatch(presenterSub , currPresenter , 
                            content,contentType,sender);
                }
                catch(Exception ex)
                {
                    sop("Exception while sending meeting mail to the presenter:"
                            +presenter+"*******Topic:"+topic,"normal");
                }
                //

                //********* Participants handling ********
                //In edit meeting participants are categorized to two, new and old participants
                //participants list contains:: 
                //   <all participants list>:::existing_Participant:::<existing participants list>
                String delimeterStr = ":::existing_Participant:::";
                int lnOfStr = delimeterStr.length();
                int indx = participantsList.indexOf(delimeterStr);
                String allparticipants = participantsList.substring(0,indx);
                String extpart = participantsList.substring((indx+lnOfStr));
                if(allparticipants != null && !allparticipants.trim().equals(""))
                {
                    String[] allMailArr = allparticipants.split(",");
                    int allLn = allMailArr.length;
                    //Having the all participants list in vector form.
                    //So that comparing and removing the mailIds present
                    //in the existing mails Ids from the all MailIds list 
                    //will be easier.
                    Vector tmpVect = new Vector();
                    for(int k = 0 ; k < allLn ; k++ )
                    {
                        if(!tmpVect.contains(allMailArr[k]))
                        {
                            tmpVect.add(allMailArr[k]);
                        }
                    }


                    if(extpart != null && !extpart.trim().equals(""))
                    {
                        String[] exMailIds = extpart.split(",");
                        int exLn = exMailIds.length;
                        for(int j = 0 ; j < exLn ; j++ )
                        {
                            //removing this mail id from all participants list
                            String tmp = exMailIds[j];
                            if(tmp != null && !tmp.trim().equals(""))
                            {
                                // ****
                                //If the existing participant is in the all participants
                                //list, removing the same from the all pariticipants list
                                //and sending updated mail to the user. 
                                // ****
                                //If the email Id present in the existing participants and
                                //not present in the all participants, not sending any
                                //mail to the corresponding email Id. This case occurs,
                                //when user removed an existing e-mail id while editing.
                                // ****
                                if(tmpVect.contains(tmp))
                                {
                                    tmpVect.remove(tmp);
                                    //Sending mail to the existing user
                                    content = getContent( tmp , "participant" , updateMessage);
                                    try
                                    {
                                        String responsePar = mu.despatch(subjectOnEdit ,tmp , 
                                                content , contentType,sender);
                                    }
                                    catch(Exception sx)
                                    {
                                        sop("Exception while sending meeting mail to the"+
                                                " participant:"+tmp+"** Topic:"+topic,"normal");
                                    }
                                }
                            }
                        }
                    }
                    if(tmpVect.isEmpty() || tmpVect.size() == 0)
                    {
                        participantsList = "";
                    }
                    else
                    {
                        participantsList = "";
                        //Forming the all participants list from the tmpVect which
                        //contains only the newly added participants
                        for(int t = 0 ; t < tmpVect.size() ; t++ )
                        {
                            if(participantsList.trim().equals(""))
                            {
                                participantsList = tmpVect.get(t).toString();
                            }
                            else
                            {
                                if( !(tmpVect.get(t).toString()).trim().equals("") )
                                {
                                    participantsList = participantsList + "," + tmpVect.get(t).toString();
                                }
                            }
                        }
                    }
                }
                //No participants to invite
                else
                {
                    return;
                }
            }
           
    
            
            //Sends mail to participants on creating , 
            //editing (for new participants) and inviting meeting

            //
            subject = "ZohoConnect Meeting Invite: "+topic;

            //Participants
            String[] mailIds = participantsList.split(",");
            int ln = mailIds.length;
            if(ln > 0)
            {
                for( int i = 0 ; i < ln ; i++ )
                {
                    String mailId = mailIds[i];
                    if(mailId.trim().equals(""))
                    {
                        continue;
                    }
                    content = getContent( mailId , "participant" , inviteMessage);
                    try
                    {
                        String responsePar = mu.despatch(subject ,mailId , 
                                content , contentType,sender);
                    }
                    catch(Exception sx)
                    {
                        sop("Exception while sending meeting mail to the"+
                                " participant:"+mailId+"** Topic:"+topic,"normal");
                    }
                }
            }
        }
        catch(Exception e)
        {
            sop("Exception in sending meeting mail::topic:*"
                    +topic+"topic","normal");
            e.printStackTrace();    
        }
    }

    //
    private String getContent(String mailid, String type , String inviteOrUpdateMessage)
    {
        String url = path+"/jsp/meetingview.jsp?key="+meetingKey;
        String opr = "";
        if(type.equals("participant"))
        {
            url = url+"&operation=join";
            opr = "join";
        }
        else if(type.equals("presenter"))
        {
            url = url+"&operation=start";
            opr = "start";
        }

        String content = "<table style=\"font-face: Arial,Geneva,Helvetica,Swiss,SunSans-Regular\">"+
            "<tr><td>Dear "+mailid+",</td></tr>"+
            "<tr><td>"+
                "<br> <b>"+thisUser+"</b> "+inviteOrUpdateMessage+". Here is your access details."+ "<br><br>"+
                   "<table border=\"0\" cellpadding=\"10\" cellspacing=\"0\" width=\"100%\">"+
                      "<tbody>"+
                         "<tr height=\"100\">"+
                            "<td height=\"86\" width=\"30\"><br></td>"+
                            "<td style=\"border: 1px solid rgb(204, 204, 204); background-color: rgb(244, 244, 244);\" height=\"86\" width=\"520\">"+
                                "<table align=\"center\" border=\"0\" cellpadding=\"3\" cellspacing=\"2\" width=\"95%\">"+
                                   "<tbody>"+
                                      "<tr>"+
                                         "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\">Topic:</font></td>"+
                                        "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\">"+topic+"</font></td>"+
                                      "</tr>"+
                                      "<tr>"+
                                         "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\">Time:</font></td>"+
                                         "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\">"+ttime+"&nbsp;"+timezone+"</font></td>"+
                                      "</tr>"+
                                      "<tr>"+
                                          "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\">Agenda:</font></td>"+
                                          "<td>"+agenda+"</td>"+
                                      "</tr>"+
                                      "<tr>"+
                                          "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\">Presenter:</font></td>"+
                                          "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\"><a    href=\"mailto:"+presenter+"\">"+presenter+"</a></font></td>"+
                                      "</tr>"+
                                      "<tr>"+
                                          "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\">MeetingKey:</font></td>"+
                                          "<td><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\">"+meetingKey+"</font></td>"+
                                       "</tr>"+
                                       "<tr>"+
                                          "<td colspan=\"2\"><fontface=\"Arial,Geneva,Helvetica,Swiss,SunSans-Regular\" size=\"2\"><a href=\""+url+"\">Click here to "+opr+" meeting</a></font></td>"+
                                       "</tr>"+
                                   "</tbody>"+
                                "</table>"+
                             "</td>"+
                             "<td height=\"86\"><br>"+
                             "</td>"+
                         "</tr>"+
                       "</tbody>"+
                    "</table><br>"+
                    "Please contact "+thisUser+" for further details and clarifications.<br><br><br>"+
                "Thanks,<br><br>ZohoConnect Team<br><br>"+
            "</td></tr>"+
            "</table>";
        return content;
    }
    
    // Sample response for create meeting:::
    //{"response":
    //      {"uri":"/api/private/json/meetings/createMeeting","result":{"meeting":{"meetingKey":"299070000000014853"}}}}
    private void setMeetingKey()
    {
        if(response != null && !response.trim().equals(""))
        {
            String startStr = "meetingKey\":\"";
            int indx = response.indexOf("meetingKey\":\"");
            int ln = startStr.length();
            String arr1 = response.substring((indx+ln));
            String[] arr2 = arr1.split("\"");
            meetingKey = arr2[0];
        }
    }

    //
    private void sop(String message,String type)
    {
     //   ZohoUtil.printInLog("SendMeetingLink::"+message,type);
    }
}
