/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author arvind raghavan
 */
public class NewMeeting extends HttpServlet {

    Properties props = new Properties();

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
        } finally {
            out.close();
        }
    }

    @Override
    public void init() {
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");


    }

    public boolean sendEmail(final String[] fromEmail, String[] email, String[] meetingdetails) {
        try {

            Session s = Session.getInstance(props, new javax.mail.Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromEmail[0], fromEmail[1]);
                }
            });
            InternetAddress from = new InternetAddress(fromEmail[0]);
            MimeMessage message = new MimeMessage(s);
            message.setFrom(from);


            InternetAddress[] addressTo = new InternetAddress[email.length];
            for (int i = 0; i < email.length; i++) {

                addressTo[i] = new InternetAddress(email[i]);
            }

            message.setRecipients(Message.RecipientType.TO, addressTo);
            message.setSubject("Meeting Invite");

            String invitation = "A new meeting is organised.\n\n The details of venue and timings are given below :\n\n";
            for (int i = 0; i < meetingdetails.length; ++i) {
                invitation += meetingdetails[i] + "\n\n";
            }
            message.setText(invitation);
            Transport.send(message);


            return true;
        } catch (MessagingException ex) {
            Logger.getLogger(NewMeeting.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

            doPost(request, response);

    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                String id = (String) (request.getSession().getAttribute("id"));
        String[] inviter = DataBase.getEmailIDPassword(id);

        String[] meetingdetails = request.getParameterValues("meetingDetails");
        
        
        String[] activeParticipants = request.getParameterValues("activelist");
        String[] participants = request.getParameterValues("participantlist");
        
        String agenda=request.getParameter("txtAgenda");
        System.out.println(agenda);
        
        String[] activemailids = new String[activeParticipants.length];
        String[] activeids = new String[activeParticipants.length];
        
        int activecount = 0;
        String[] parmailids = new String[participants.length];
        String[] parids = new String[participants.length];
        
        System.out.println("length :"+participants.length);
        int parcount = 0;

        for (int i = 0; i < activeParticipants.length; ++i) {
            try {
                String empid = activeParticipants[i].substring(activeParticipants[i].indexOf("-") + 1);
                
                Connection con = DataBase.getConnection();
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("select * from signup where empid='" + empid + "'");
                if (rs.next()) {
                    activemailids[activecount] = rs.getString("email");
                    activeids[activecount] = rs.getString("empid");
                    ++activecount;

                }

            } catch (SQLException ex) {
                Logger.getLogger(NewMeeting.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        for (int j = 0; j < participants.length; ++j) {
            try {
                String empid = participants[j].substring(participants[j].indexOf("-") + 1);
                Connection con = DataBase.getConnection();
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery("select * from signup where empid='" + empid + "'");
                if (rs.next()) {
                    parmailids[parcount] = rs.getString("email");
                    parids[parcount] = rs.getString("empid");
                    ++parcount;
                }

            } catch (SQLException ex) {
                Logger.getLogger(NewMeeting.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        try {
            Connection con = DataBase.getConnection();
            int room_id =0;
            Statement stmt = con.createStatement();
            int[] mids=new int[meetingdetails.length];
            String[] startDate=new String[meetingdetails.length];
            String[] endDate=new String[meetingdetails.length];
            int meetID=0; int count=0;
            for (int i = 0; i < meetingdetails.length; ++i) {
                String temp = meetingdetails[i];
                String roomid = temp.substring(0, temp.indexOf("/") - 1);
                room_id= Integer.parseInt(roomid);
                String tmp = temp.substring(temp.indexOf(":") + 2);
                String starttime = tmp.substring(0, tmp.indexOf("-"));
                String endtime = tmp.substring(tmp.indexOf("-") + 1, tmp.length() - 2);
                String starttimestamp = parseDate(starttime);
                String endtimestamp = parseDate(endtime);
                stmt.executeUpdate("INSERT INTO sdms.scheduledmeetings (startDateTime,roomid,status,endDateTime,empid,is_active,agenda)" +
                        "VALUES('" + starttimestamp + "'," + room_id + ",5,'" + endtimestamp + "','" + id + "',5,'"+agenda+"')");
                startDate[meetID]=starttimestamp;
                endDate[meetID]=endtimestamp;
                ++meetID;
            }
            
            for(int i=0;i<meetID;++i){
                ResultSet rs= stmt.executeQuery("select * from scheduledmeetings where startDateTime='"+startDate[i]+"' and endDateTime='"+endDate[i]+"' and agenda='"+agenda+"' and empid='"+id+"'");
                if(rs.next()){
                    mids[count]=rs.getInt("meetingid");
                    ++count;
                }
            }
            
            for(int i=0;i<activeids.length;++i){
                if(id.equals(activeids[i])){
                  stmt.executeUpdate("update scheduledmeetings set is_active=1 where empid='"+id+"'");  
                    continue;
                }
                for(int j=0;j<mids.length;++j){
                     stmt.executeUpdate("insert into sdms.scheduledmeetings(meetingid,startDateTime,roomid,status,endDateTime,empid,is_active,agenda) values("+mids[j]+",'"+startDate[j]+"',"+room_id+"," +
                           "0,'"+endDate[j]+"','"+activeids[i]+"',1,'"+agenda+"')");
               }
           }
           System.out.println("parid length :"+parids.length);
           for(int i=0;i<parids.length;++i){
                if(id.equals(parids[i])){
                  stmt.executeUpdate("update scheduledmeetings set is_active=0 where empid='"+id+"'");  
                    continue;
                }
                System.out.println("parid :"+parids[i]);
                for(int j=0;j<mids.length;++j){
                   stmt.executeUpdate("insert into sdms.scheduledmeetings(meetingid,startDateTime,roomid,status,endDateTime,empid,is_active,agenda) values("+mids[j]+",'"+startDate[j]+"',"+room_id+"," +
                           "0,'"+endDate[j]+"','"+parids[i]+"',0,'"+agenda+"')");
                }
           }
            System.out.println("Insertion Success!!!");
                      
        } catch (SQLException e) {
            e.printStackTrace();
        }

        boolean flg1 = sendEmail(inviter, activemailids, meetingdetails);
        boolean flg2 = sendEmail(inviter, parmailids, meetingdetails);

        if (flg1 && flg2) {
        response.sendRedirect("confirmPage.jsp");
        }
    }

    /** 
     * Returns a short description of the servlet.
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public String parseDate(String str) {
        String startdate = str.substring(0, str.indexOf("["));
        String sttime = str.substring(str.indexOf("[") + 1, str.length() - 1);

        Date stdt = new Date(startdate);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String newstDate = sdf.format(stdt);


        sdf = new SimpleDateFormat("HH:mm:ss");
        Date sttd = new Date(startdate + " " + sttime);

        String newstTime = sdf.format(sttd);
        String starttimestamp = newstDate + " " + newstTime;

        return starttimestamp;

    }
}
