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

import java.io.IOException;
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.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

    /** 
     * 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 {
            response.setContentType("text/html;charset=UTF-8");
            String[] meetingdates = request.getParameterValues("dateList");
            String[] equiplist = request.getParameterValues("equipments");
            String[] proposeDateList = request.getParameterValues("proposedatelist");
            String id = (String) request.getSession().getAttribute("id");
            String agenda = request.getParameter("txtAgenda");
            Hashtable ht = (Hashtable) request.getSession().getAttribute("entries");
            boolean flg=false;
            if(ht==null){
                ht=(Hashtable) request.getSession().getAttribute("reentries");
                 flg=true;
            }
            
            Integer isActive = (Integer) ht.get("isactive");
            int isactive = isActive.intValue();
            int[] meetingIDs = new int[100];
            int count = 0;
            Connection con = DataBase.getConnection();
            Statement st = con.createStatement();
            int room_id = 0;
            
            if (proposeDateList!=null&&proposeDateList.length > 0) {
                String[] datetimepairs = (String[]) ht.get("datetimepairs");
                for (int i = 0; i < datetimepairs.length; ++i) {
                    if (datetimepairs[i] == null) {
                        break;
                    }
                    String starttime = datetimepairs[i].substring(0, datetimepairs[i].indexOf("-"));
                    String endtime = datetimepairs[i].substring(datetimepairs[i].indexOf("-") + 1);
                    String starttimestamp = parseDate(starttime);
                    String endtimestamp = parseDate(endtime);
                    String q1="select meetingid from scheduledmeetings where agenda='" + agenda + "' and empid='" + id + "' and status=0 " +
                            "and startDateTime='" + starttimestamp + "' and endDateTime='" + endtimestamp + "'";
                    String q2="select meetingid from scheduledmeetings where agenda='" + agenda + "' and empid='" + id + "' and status=3 " +
                            "and startDateTime='" + starttimestamp + "' and endDateTime='" + endtimestamp + "'";
                    ResultSet rs=null;
                    if(!flg){
                         rs = st.executeQuery(q1);
                    }
                    else{
                        rs=st.executeQuery(q2);
                    }
                    if (rs.next()) {
                        st.executeUpdate("delete from equipreq where empid='" + id + "' and meetingid=" + rs.getInt("meetingid"));
                        st.executeUpdate("delete from scheduledmeetings where empid='" + id + "' and agenda='" + agenda + "'and startDatetime='" + starttimestamp + "' and endDateTime='" + endtimestamp + "' and status=0");
                        System.out.println("Delete Success!!");
                    }
                }
                for (int i = 0; i < proposeDateList.length; ++i) {
                    //flg = true;
                    System.out.println("In for loop");
                    if (proposeDateList[i] == null) {
                        break;
                    }
                    String temp = proposeDateList[i];
                    System.out.println(proposeDateList[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);
                    st.executeUpdate("insert into scheduledmeetings(startDateTime,roomid,status," +
                            "endDateTime,empid,is_active,Agenda)" +
                            "values('" + starttimestamp + "'," + room_id + "," +
                            "4,'" + endtimestamp + "','"+id+"'," + isactive + ",'" + agenda + "')");
                    System.out.println("insert into scheduledmeetings(startDateTime,roomid,status," +
                            "endDateTime,empid,is_active,Agenda)" +
                            "values('" + starttimestamp + "'," + room_id + "," +
                            "4,'" + endtimestamp + "','"+id+"'," + isactive + ",'" + agenda + "')");
                    System.out.println("Insert Success!!");

                }
            } else {
                    
                for (int i = 0; i < meetingdates.length; ++i) {
                    if (meetingdates[i] != null) {
                        String datetimepair = meetingdates[i];
                        String starttime = datetimepair.substring(0, datetimepair.indexOf("-"));
                        String endtime = datetimepair.substring(datetimepair.indexOf("-") + 1);
                        String starttimestamp = parseDate(starttime);
                        String endtimestamp = parseDate(endtime);
                        String q1="select meetingid from scheduledmeetings where agenda='" + agenda + "' and empid='" + id + "' and status=0 " +
                            "and startDateTime='" + starttimestamp + "' and endDateTime='" + endtimestamp + "'";
                        String q2="select meetingid from scheduledmeetings where agenda='" + agenda + "' and empid='" + id + "' and status=3 " +
                            "and startDateTime='" + starttimestamp + "' and endDateTime='" + endtimestamp + "'";
                         ResultSet rs=null;
                         if(flg){
                             rs=st.executeQuery(q2);
                         }
                         else{
                             rs=st.executeQuery(q1);
                         }
                        
                        if (rs.next()) {
                            
                            int meetid =0;
                            meetid=meetingIDs[count] = rs.getInt("meetingid");
                            ++count;
                            st.executeUpdate("Update scheduledmeetings set status=1 where meetingid=" + meetid + " and empid='" + id + "'");
                            System.out.println("Delete from scheduledmeetings where empid='" + id + "'"+
                                    " and meetingid <> "+meetid+" and status=0 and agenda='"+agenda+"'");
                            st.executeUpdate("Delete from scheduledmeetings where status=0 and empid='"+id+"' and agenda='"+agenda+"' and meetingid <>"+meetid);
                            
                         }
                    }
                }

                if (isactive == 1 && equiplist!=null) {
                    int[] equipmentids = new int[200];
                    int equipcount = 0;
                    for (int i = 0; i < equiplist.length; ++i) {
                        ResultSet rs = st.executeQuery("select equipmentid from equipmentlist where equipmentName='" + equiplist[i] + "'");
                        while (rs.next()) {
                            equipmentids[equipcount] = rs.getInt("equipmentid");
                            ++equipcount;
                        }
                    }
                    for (int i = 0; i < count; ++i) {
                        for (int j = 0; j < equipcount; ++j) {
                            st.executeUpdate("insert into equipreq values(" + meetingIDs[i] + ",'" + id + "'," + equipmentids[j] + ")");
                        }
                    }
                    }

            }
             System.out.println("Update and Insert Success");
                    response.sendRedirect("acceptedMeeting.jsp");
               
        } catch (SQLException ex) {
            Logger.getLogger(AcceptMeeting.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    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;

    }

    // <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 {
        doPost(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>
}
