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

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DataEntryBean.GovtOrderCreationDetailBean;
import DataEntryBean.GovtOrderCreationExpenseBean;
import DataEntryBean.GovtOrderCreationHeaderBean;
import DataEntryBean.DepositRateSlabBean;
import LoginDb.DbHandler;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author 590685
 */
public class DepositRateSlabServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {

        HttpSession session = request.getSession(false);
        Connection con = null;
        Connection con1 = null;
        CallableStatement stmt = null;
        CallableStatement proc = null;
        String message = "";
        
        //String pacsId = (String) session.getAttribute("pacsId");
        String tellerId = (String) session.getAttribute("user");

        String ServletName = request.getParameter("handle_id");
       // String dep_product_id = request.getParameter("dep_product_id");
       // String procStartDate = request.getParameter("procStartDate");
        //String procEndDate = request.getParameter("procEndDate");
        String pacsId = (String) session.getAttribute("pacsId");
       // String tellerId = (String) session.getAttribute("tellrId");
        
        DepositRateSlabBean oDepositRateSlabBean = new DepositRateSlabBean();
        DepositRateSlabBean oDepositRateSlabBeanHeader = new DepositRateSlabBean();
        ArrayList<DepositRateSlabBean> alDepositRateSlabBean = new ArrayList<DepositRateSlabBean>();
        ArrayList<DepositRateSlabBean> alDepositRateSlabBeanNew = new ArrayList<DepositRateSlabBean>();
        ArrayList<DepositRateSlabBean> alDepositRateSlabBeanUpdated = new ArrayList<DepositRateSlabBean>();
        ArrayList<DepositRateSlabBean> alDepositRateSlabBeanDeleted = new ArrayList<DepositRateSlabBean>();

       
        try {
           // BeanUtils.populate(oDepositRateSlabBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(AccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(AccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        }
       
        if ("Create".equalsIgnoreCase(ServletName)) {

            int counter = Integer.parseInt(request.getParameter("rowCounter"));


            for (int i = 1; i <= counter; i++) {
                try {

                    //String inttRate = request.getParameter("inttRate" + i);
                    //String termFrom = request.getParameter("termFrom" + i);
                   // String termTo = request.getParameter("termTo" + i);
                    //String amountFrom = request.getParameter("amountFrom" + i);
                    //String amountTo = request.getParameter("amountTo" + i);

                    if (dep_product_id != null && inttRate != null&& termFrom != null&& termTo != null&& amountFrom != null&& amountTo != null) {
                        oDepositRateSlabBean = new DepositRateSlabBean();
                        oDepositRateSlabBean.setInttRate(inttRate);
                        oDepositRateSlabBean.setTermFrom(termFrom);
                        oDepositRateSlabBean.setTermTo(termTo);
                        oDepositRateSlabBean.setAmountFrom(amountFrom);
                        oDepositRateSlabBean.setAmountTo(amountTo);
                        oDepositRateSlabBean.setProcStartDate(procStartDate);
                        oDepositRateSlabBean.setProcEndDate(procEndDate);

                        alDepositRateSlabBean.add(oDepositRateSlabBean);
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }

            if (alDepositRateSlabBean.size() > 0) {
                try {
                    con1 = DbHandler.getDBConnection();
                    stmt = con1.prepareCall("{ call operations.upsert_td_rate_slab(?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    for (int j = 0; j < alDepositRateSlabBean.size(); j++) {
                        oDepositRateSlabBean = alDepositRateSlabBean.get(j);
                        stmt.setString(1, dep_product_id);
                        stmt.setString(2, "");
                        stmt.setString(3, oDepositRateSlabBean.getInttRate());
                        stmt.setString(4, oDepositRateSlabBean.getTermFrom());
                        stmt.setString(5, oDepositRateSlabBean.getTermTo());
                        stmt.setString(6, oDepositRateSlabBean.getAmountFrom());
                        stmt.setString(7, oDepositRateSlabBean.getAmountTo());
                        stmt.setString(8, oDepositRateSlabBean.getProcStartDate());
                        stmt.setString(9, oDepositRateSlabBean.getProcEndDate());
                        stmt.setString(10, "Create");
                        stmt.setString(11, pacsId);
                        stmt.setString(12, tellerId);
                        stmt.registerOutParameter(13, java.sql.Types.VARCHAR);

                        stmt.execute();
                        //proc.addBatch();

                    }
                    //proc.executeBatch();
                    //message = stmt.getString(13);

                } catch (SQLException ex) {
                   // String delete = "Delete from TD_RATE_SLAB where PRODUCT_ID = '" + dep_product_id + "' ";
                   String delete = "Delete from TD_RATE_SLAB where PRODUCT_ID = '" + dep_product_id + "' and pacs_id='" + pacsId +"'";
                    Connection conn = DbHandler.getDBConnection();
                    PreparedStatement pstmt = conn.prepareCall(delete);
                    pstmt.executeQuery();
                    if (conn != null) {
                       // conn.commit();
                        conn.close();
                    }
                   // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                
                } finally {
                   try {
                       if (con1 != null) {
                       // conn.commit();
                        con1.close();
                        }
                   } catch (Exception e){
                       System.out.println("Error occurred during connection close.");
                   }   
                }

            }




            request.setAttribute("message", message);
            request.getRequestDispatcher("/Deposit/DepositRateSlab.jsp").forward(request, response);

        } else if ("Search".equalsIgnoreCase(ServletName)) {

           // dep_product_id = request.getParameter("dep_product_id");


            Connection connection = null;
            ResultSet resultset = null;
            Statement statement = null;
            connection = DbHandler.getDBConnection();
            int SeachFound = 0;

            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
              //  Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {

                //ResultSet rs = statement.executeQuery("select  distinct to_char(t.eff_from_date,'dd/mm/yyyy') as from_date,to_char(t.eff_to_date,'dd/mm/yyyy') as to_date,p.prod_code,p.int_cat,p.prod_desc,p.intt_cat_desc,p.id from  TD_RATE_SLAB t,dep_product p where t.product_id = p.id and t.product_id = '" + dep_product_id + "' and t.pacs_id='"+ pacsId +"'");

                while (rs.next()) {

                    oDepositRateSlabBeanHeader.setpCodeSearch(rs.getString("prod_code") + " : " + rs.getString("prod_desc"));
                    oDepositRateSlabBeanHeader.setiCatSearch(rs.getString("int_cat") + " : " + rs.getString("intt_cat_desc"));
                    oDepositRateSlabBeanHeader.setProcStartDate(rs.getString("from_date"));
                    oDepositRateSlabBeanHeader.setProcEndDate(rs.getString("to_date"));
                    oDepositRateSlabBeanHeader.setDep_product_id(rs.getString("id"));

                    SeachFound = 1;
                    request.setAttribute("displayFlag", "Y");

                }

                statement.close();
                rs.close();;

            } catch (SQLException ex) {
               // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }

            if (SeachFound == 0) {
                message = "Product does not exist in the system or Product is not tagged to any Rate Slab entry";
                request.setAttribute("message", message);
            }

            
            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }
            try {

              //  String query = "select t.rate, t.term_from, t.term_to, t.from_amt, t.to_amt, t.id as slap_table_id,p.prod_code,p.int_cat,p.prod_desc,p.intt_cat_desc,t.product_id from  TD_RATE_SLAB t,dep_product p where t.product_id = p.id and t.product_id = '" + dep_product_id + "' order by t.rate asc ";
              String query = "select t.rate, t.term_from, t.term_to, t.from_amt, t.to_amt, t.id as slap_table_id,p.prod_code,p.int_cat,p.prod_desc,p.intt_cat_desc,t.product_id from  TD_RATE_SLAB t,dep_product p where t.product_id = p.id and t.product_id = '" + dep_product_id + "' and t.pacs_id ='" + pacsId + "' order by t.rate asc ";
               // ResultSet rs = statement.executeQuery(query);

                while (rs.next()) {

                    oDepositRateSlabBean = new DepositRateSlabBean();
                    oDepositRateSlabBean.setDep_product_id(rs.getString("product_id"));
                    oDepositRateSlabBean.setSlabTable_id(rs.getString("slap_table_id"));
                    oDepositRateSlabBean.setInttRate(rs.getString("rate"));
                    oDepositRateSlabBean.setAmountFrom(rs.getString("from_amt"));
                    oDepositRateSlabBean.setAmountTo(rs.getString("to_amt"));
                    oDepositRateSlabBean.setTermFrom(rs.getString("term_from"));
                    oDepositRateSlabBean.setTermTo(rs.getString("term_to"));


                    alDepositRateSlabBean.add(oDepositRateSlabBean);

                }

                statement.close();
                rs.close();


            } catch (SQLException ex) {
               // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                connection.close();
            }

           // connection.close();

            request.setAttribute("oDepositRateSlabBean", oDepositRateSlabBeanHeader);
            request.setAttribute("alDepositRateSlabBean", alDepositRateSlabBean);

            request.getRequestDispatcher("/Deposit/DepositRateSlab.jsp").forward(request, response);

        } else if ("Update".equalsIgnoreCase(ServletName)) {

            //String procStartDateAmend = request.getParameter("procStartDateAmend");
           // String procEndDateAmend = request.getParameter("procEndDateAmend");
            int add = Integer.parseInt(request.getParameter("add"));
            int counterfor_Detail = Integer.parseInt(request.getParameter("rowCounterAmend"));
            counterfor_Detail = counterfor_Detail + add;

            for (int i = 1; i <= counterfor_Detail; i++) {
                try {

                   // String inttRateAmend = request.getParameter("inttRateAmend" + i);
                   // String termFromAmend = request.getParameter("termFromAmend" + i);
                  //  String termToAmend = request.getParameter("termToAmend" + i);
                   // String amountFromAmend = request.getParameter("amountFromAmend" + i);
                   // String amountToAmend = request.getParameter("amountToAmend" + i);
                    String rowStatus = request.getParameter("rowStatus" + i);
                   // String detailID = request.getParameter("slabTable_id" + i);

                    if ( inttRateAmend != null && termFromAmend != null && termToAmend != null && amountFromAmend != null && amountToAmend != null && rowStatus != null && detailID != null) {
                        oDepositRateSlabBean = new DepositRateSlabBean();
                        oDepositRateSlabBean.setInttRateAmend(inttRateAmend);
                        oDepositRateSlabBean.setTermFromAmend(termFromAmend);
                        oDepositRateSlabBean.setTermToAmend(termToAmend);
                        oDepositRateSlabBean.setAmountFromAmend(amountFromAmend);
                        oDepositRateSlabBean.setAmountToAmend(amountToAmend);
                        oDepositRateSlabBean.setSlabTable_id(detailID);

                        if (rowStatus.equals("N")) {
                            alDepositRateSlabBeanNew.add(oDepositRateSlabBean);
                        } else {
                            alDepositRateSlabBeanUpdated.add(oDepositRateSlabBean);
                        }


                    }

                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }

            //For Deletion

           // String deletedRows = request.getParameter("deletedRows");


            if ((!deletedRows.equalsIgnoreCase(null)) || (!deletedRows.equalsIgnoreCase(""))) {
                StringTokenizer tokenizer = new StringTokenizer(deletedRows, ",");

                while (tokenizer.hasMoreTokens()) {

                    oDepositRateSlabBean = new DepositRateSlabBean();
                    oDepositRateSlabBean.setSlabTable_id(tokenizer.nextToken());

                    alDepositRateSlabBeanDeleted.add(oDepositRateSlabBean);

                }
            }




            if (alDepositRateSlabBeanUpdated.size() > 0) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{ call operations.upsert_td_rate_slab(?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }


                    for (int j = 0; j < alDepositRateSlabBeanUpdated.size(); j++) {

                        oDepositRateSlabBean = alDepositRateSlabBeanUpdated.get(j);


                        proc.setString(1, dep_product_id);
                        proc.setString(2, oDepositRateSlabBean.getSlabTable_id());
                        proc.setString(3, oDepositRateSlabBean.getInttRateAmend());
                        proc.setString(4, oDepositRateSlabBean.getTermFromAmend());
                        proc.setString(5, oDepositRateSlabBean.getTermToAmend());
                        proc.setString(6, oDepositRateSlabBean.getAmountFromAmend());
                        proc.setString(7, oDepositRateSlabBean.getAmountToAmend());
                        proc.setString(8, procStartDateAmend);
                        proc.setString(9, procEndDateAmend);
                        proc.setString(10, "Update");
                        proc.setString(11, pacsId);
                        proc.setString(12, tellerId);
                        proc.registerOutParameter(13, java.sql.Types.VARCHAR);

                        proc.execute();
                        //proc.addBatch();                        
                    }
                    //proc.executeBatch();
                  //  message = proc.getString(13);                    
                    

                } catch (SQLException ex) {
                   // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }

            //for deletion

            if (alDepositRateSlabBeanDeleted.size() > 0) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{ call operations.upsert_td_rate_slab(?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }


                    for (int j = 0; j < alDepositRateSlabBeanDeleted.size(); j++) {

                        oDepositRateSlabBean = new DepositRateSlabBean();

                        oDepositRateSlabBean = alDepositRateSlabBeanDeleted.get(j);


                        proc.setString(1, dep_product_id);
                        proc.setString(2, oDepositRateSlabBean.getSlabTable_id());
                        proc.setString(3, oDepositRateSlabBean.getInttRateAmend());
                        proc.setString(4, oDepositRateSlabBean.getTermFromAmend());
                        proc.setString(5, oDepositRateSlabBean.getTermToAmend());
                        proc.setString(6, oDepositRateSlabBean.getAmountFromAmend());
                        proc.setString(7, oDepositRateSlabBean.getAmountToAmend());
                        proc.setString(8, procStartDateAmend);
                        proc.setString(9, procEndDateAmend);
                        proc.setString(10, "Delete");
                        proc.setString(11, pacsId);
                        proc.setString(12, tellerId);
                        proc.registerOutParameter(13, java.sql.Types.VARCHAR);                       
                        //proc.addBatch();
                        proc.execute();
                        //proc.executeBatch();
                    }
                    //proc.executeBatch();
                  //  message = proc.getString(13);


                } catch (SQLException ex) {
                   // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }

            //For New Insertion


            if (alDepositRateSlabBeanNew.size() > 0) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{call operations.upsert_td_rate_slab(?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error occurred during processing.");
                    }


                    for (int j = 0; j < alDepositRateSlabBeanNew.size(); j++) {

                        oDepositRateSlabBean = new DepositRateSlabBean();

                        oDepositRateSlabBean = alDepositRateSlabBeanNew.get(j);


                        proc.setString(1, dep_product_id);
                        proc.setString(2, oDepositRateSlabBean.getSlabTable_id());
                        proc.setString(3, oDepositRateSlabBean.getInttRateAmend());
                        proc.setString(4, oDepositRateSlabBean.getTermFromAmend());
                        proc.setString(5, oDepositRateSlabBean.getTermToAmend());
                        proc.setString(6, oDepositRateSlabBean.getAmountFromAmend());
                        proc.setString(7, oDepositRateSlabBean.getAmountToAmend());
                        proc.setString(8, procStartDateAmend);
                        proc.setString(9, procEndDateAmend);
                        proc.setString(10, "Create");
                        proc.setString(11, pacsId);
                        proc.setString(12, tellerId);
                        proc.registerOutParameter(13, java.sql.Types.VARCHAR);
                        
                        proc.execute();
                        //proc.addBatch();
                    }
                    //proc.executeBatch();
                   // message = proc.getString(13);
                    

                } catch (SQLException ex) {
                  //  Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                  //  System.out.println(ex.toString());
                  System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }

           // message = "Rate Slab updated succesfully";
            request.setAttribute("message", message);
            request.getRequestDispatcher("/Deposit/DepositRateSlab.jsp").forward(request, response);

        }



    }

    // <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
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);

        } catch (SQLException ex) {
           // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);

        } catch (SQLException ex) {
           // Logger.getLogger(DepositRateSlabServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        }
    }

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