/*
 * confirmnegotiate.java
 *
 * Created on December 1, 2008, 6:28 PM
 */

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.ArrayList;
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 Srikrishna
 * @version
 */
public class confirmnegotiate 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(negotiatemeeting.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"));
        ArrayList<ArrayList<String[]>> totallist = new ArrayList<ArrayList<String[]>>();
        totallist = (ArrayList<ArrayList<String[]>>) (request.getSession().getAttribute("totallist"));
        ArrayList<String[]> meetingids = new ArrayList<String[]>();
        ArrayList<String[]> activeList = new ArrayList<String[]>();
        ArrayList<String[]> equipList = new ArrayList<String[]>();
        String[] isactivearray = new String[100];
        String[] participantsarr = new String[100];

        
        if (!totallist.isEmpty()) {
            for (int i = 0; i < totallist.size(); i++) {
                meetingids = totallist.get(0);
                activeList = totallist.get(1);
                equipList = totallist.get(2);


                if (!activeList.isEmpty()) {

                    int parcount = 0;
                    int actcount = 0;
                    String userids = "";
                    String isactiveval = "";
                    for (int o = 0; o < activeList.size(); o++) {
                        String[] isactivearr = activeList.get(o);

                        System.out.println("count :" + o);
                        userids = isactivearr[0];
                        isactiveval = isactivearr[1];
                        System.out.println("userids" + userids);
                        System.out.println("isactiveval" + isactiveval);
                        if (isactiveval.equals('0')) {
                            participantsarr[parcount] = userids;
                            ++parcount;
                        } else {
                            isactivearray[actcount] = userids;
                            ++actcount;
                        }
                    }
                }

                if (!meetingids.isEmpty()) {
                    for (int p = 0; p < meetingids.size(); p++) {
                        try {
                            Connection con = DataBase.getConnection();
                            Statement stmt = con.createStatement();
                            String[] meetingidsarray = meetingids.get(p);
                            System.out.println("meetings idsss = " + meetingidsarray[0]);

                            System.out.println("DELETE FROM sdms.scheduledmeetings WHERE meetingid = '" + meetingidsarray[0] + "'");
                            stmt.executeUpdate("DELETE FROM sdms.scheduledmeetings WHERE meetingid = '" + meetingidsarray[0] + "'");
                        } catch (SQLException ex) {
                            ex.printStackTrace();
                        }

                    }
                }

            }

        }

        String[] inviter = DataBase.getEmailIDPassword(id);

        String[] meetingdetails = request.getParameterValues("datetimelist");

        String[] participants = participantsarr;
        String[] activeParticipants = isactivearray;
        String agenda = (String) request.getSession().getAttribute("agenda");
        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 < isactivearray.length; ++i) {
            try {
                String empid = isactivearray[i];

                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(negotiatemeeting.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        System.out.println("activemail id : "+activemailids.length);
       
        for (int j = 0; j < participantsarr.length; ++j) {
            try {
                String empid = participantsarr[j];
                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(negotiatemeeting.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(activeids[i] == null)
                {
                    break;
                }
                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++) {
                    System.out.println("insert into sdms.scheduledmeetings(meetingid,startDateTime,roomid,status,endDateTime,empid,is_active,agenda) values(" + mids[j] + ",'" + startDate[j] + "'," + room_id + "," +
                            "3,'" + endDate[j] + "','" + activeids[i] + "',1,'" + agenda + "')");
                    stmt.executeUpdate("insert into sdms.scheduledmeetings(meetingid,startDateTime,roomid,status,endDateTime,empid,is_active,agenda) values(" + mids[j] + ",'" + startDate[j] + "'," + room_id + "," +
                            "3,'" + endDate[j] + "','" + activeids[i] + "',1,'" + agenda + "')");

                }
            }
            System.out.println("parid length :" + parids.length);
            for (int i = 0; i < parids.length; i++) {
                if(parids[i] == null)
                {
                    break;
                }
                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 + "," +
                            "3,'" + endDate[j] + "','" + parids[i] + "',0,'" + agenda + "')");
                }
            }
            System.out.println("Insertion Success!!!");
            int counts = 0;
            int[] meetingidsintarr = new int[100];
            if (!equipList.isEmpty()) {
                try {
                    ResultSet rs5 = stmt.executeQuery("select distinct meetingid from scheduledmeetings where agenda in " +
                            "(select agenda from scheduledmeetings where empid='" + id + "' and agenda='" + agenda + "' and status=5)");
                    if (rs5.next()) {
                        meetingidsintarr[counts] = rs5.getInt("meetingid");
                        ++counts;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                for (int p = 0; p < equipList.size(); p++) {
                    try {

                        String[] equipListarray = equipList.get(p);
                        System.out.println("equipList idsss = " + equipListarray[0]);
                        System.out.println("equipList idsss = " + equipListarray[1]);

                        for (int j = 0; j < meetingidsintarr.length; ++j) {
                            System.out.println("INSERT   INTO sdms.equipreq (empid, equipid, meetingid) " +
                                    "VALUES ('" + meetingidsintarr[0] + "', '" + equipListarray[0] + "', '" + equipListarray[1] + "')");
                            stmt.executeUpdate("INSERT   INTO sdms.equipreq (empid, equipid, meetingid) " +
                                    "VALUES ('" + meetingidsintarr[0] + "', '" + equipListarray[0] + "', '" + equipListarray[1] + "')");
                        }
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }



                }

            }
        } 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;

    }

    public String updatetable() {

        return null;
    }
}

