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


import java.sql.ResultSet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
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 MeetingConfirmed 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 {
        try {
            String id = (String) request.getSession().getAttribute("id");
            request.getSession().setAttribute("id", id);
            String meetid = request.getParameter("meetingid");
            Integer i = new Integer(meetid);
            int meetingid = i.intValue();
            Connection con = DataBase.getConnection();
            Statement st=con.createStatement();
            ResultSet rs=st.executeQuery("select * from scheduledmeetings where meetingid="+meetingid);
            String[] time=new String[2];
            if(rs.next()){
                
                int roomid=rs.getInt("roomid");
                Timestamp start=rs.getTimestamp("startDateTime");
                Timestamp end=rs.getTimestamp("endDateTime");
                SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy [HH:mm]");
                time[0] = sdf.format(start);
                time[1]=sdf.format(end);
                ResultSet emprs =st.executeQuery("select empid from scheduledmeetings where meetingid="+meetingid+" and status <> 5");
                String[] empids=new String[200];
                int count=0;
                while(emprs.next()){
                    String emp=emprs.getString("empid");
                    empids[count]=emp;
                    System.out.println("empid : " +empids[count]);
                    ++count;
                }
                System.out.println("Empid Length :"+ count);
                System.out.println("insert into bookedrooms values('"+id+"',"+roomid+",'"+start+"','"+end+"')");
                st.executeUpdate("insert into bookedrooms values('"+id+"',"+roomid+",'"+start+"','"+end+"')");
                System.out.println("Room Booked!!!");
                String[]frommail=new String[2];
                ResultSet from=st.executeQuery("select * from signup where empid='"+id+"'" );
               // System.out.println("query executed");
                String[]toemails=new String[count];
                int qcount=0;
                if(from.next()){
                    frommail[0]=from.getString("email");
                    frommail[1]=from.getString("password");
                }
                for(int k=0;k<count;++k){
                 //  System.out.println("In for loop ");
                    ResultSet tors=st.executeQuery("select * from signup where empid='"+empids[k]+"'");
                    if(tors.next()){
                        toemails[qcount]=tors.getString("email");
                        ++qcount;
                    }
                }
                sendEmail(frommail, toemails, time[0]+" - "+time[1]);
                response.sendRedirect("MeetingConfirmed.jsp");
                
            }
        } catch (SQLException ex) {
            Logger.getLogger(MeetingConfirmed.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 
     @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 data) {
        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 = "Meeting is confirmed\n Details are given below:\n"+data;
            
            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
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

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

}
