/*
 * 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 SBRateSlabServlet 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;
        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");
        
        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>();
       
        try {
           // BeanUtils.populate(oDepositRateSlabBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           System.out.println("Error occurred during processing.");
        } catch (InvocationTargetException ex) {
           System.out.println("Error occurred during processing.");
        }
       
        if ("Search".equalsIgnoreCase(ServletName)) {

            dep_product_id = request.getParameter("dep_product_id");

            Connection connection = null;
            Statement statement = null;
            connection = DbHandler.getDBConnection();
                       
            try {
                statement = connection.createStatement();
            } catch (SQLException 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.intt_rate, t.threshold_bal, t.threshold_intt_rate, t.min_bal, t.max_bal, t.min_wdl, t.max_wdl, "
                            +" t.int_cap_freq, t.dr_txn_flag, t.dormancy, t.id, p.prod_code, p.int_cat, p.prod_desc, p.intt_cat_desc from sb_prod_map t, dep_product p where t.id = p.id and substr(p.prod_code,1,2)='11' and t.pacs_id = '" + pacsId + "' ";
               // ResultSet rs = statement.executeQuery(query);

                while (rs.next()) {

                    oDepositRateSlabBean = new DepositRateSlabBean();
                    oDepositRateSlabBean.setDep_product_id(rs.getString("id"));
                    oDepositRateSlabBean.setInttRate(rs.getString("intt_rate"));
                    oDepositRateSlabBean.setInttCapFreq(rs.getString("int_cap_freq"));
                    oDepositRateSlabBean.setProdCode(rs.getString("prod_code"));
                    oDepositRateSlabBean.setProdDesc(rs.getString("prod_desc"));
                    oDepositRateSlabBean.setInttCat(rs.getString("int_cat"));
                    oDepositRateSlabBean.setInttCatDesc(rs.getString("intt_cat_desc"));
                    oDepositRateSlabBean.setThresholdBal(rs.getString("threshold_bal"));
                    oDepositRateSlabBean.setThresholdInttRate(rs.getString("threshold_intt_rate"));
                    oDepositRateSlabBean.setMinBal(rs.getString("min_bal"));
                    oDepositRateSlabBean.setMaxBal(rs.getString("max_bal"));
                    oDepositRateSlabBean.setMinWithdraw(rs.getString("min_wdl"));
                    oDepositRateSlabBean.setMaxWithdraw(rs.getString("max_wdl"));
                    oDepositRateSlabBean.setDrTxnFlag(rs.getString("dr_txn_flag"));
                    oDepositRateSlabBean.setDormancy(rs.getString("dormancy"));


                    alDepositRateSlabBean.add(oDepositRateSlabBean);
                    request.setAttribute("displayFlag", "Y");
                }

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


            } catch (SQLException ex) {
               System.out.println("Error occurred during processing.");
            } finally {
                connection.close();
            }

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

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

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

            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 depProdId = request.getParameter("dep_product_id" +i);
                    //String inttRateAmend = request.getParameter("inttRateAmend" + i);
                    //String inttCapFreq = request.getParameter("inttCapFreq" + i);
                    String prodCode = request.getParameter("prodCode" + i);
                    String prodDesc = request.getParameter("prodDesc" + i);
                    String inttCat = request.getParameter("inttCat" + i);
                    String inttCatDesc = request.getParameter("inttCatDesc" + i);
                   // String thresholdBal = request.getParameter("thresholdBal" + i);
                   // String thresholdInttRate = request.getParameter("thresholdInttRate" + i);
                    //String minBal = request.getParameter("minBal" + i);
                    //String maxBal = request.getParameter("maxBal" + i);
                    //String minWithdraw = request.getParameter("minWithdraw" + i);
                    //String maxWithdraw = request.getParameter("maxWithdraw" + i);
                    //String drTxnFlag = request.getParameter("drTxnFlag" + i);
                    //String dormancy = request.getParameter("dormancy" + i);
                    String rowStatus = request.getParameter("rowStatus" + i);
                    String detailID = request.getParameter("slabTable_id" + i);

                    if ( depProdId!= null && inttRateAmend != null && inttCapFreq != null && prodCode != null && prodDesc != null && inttCat != null && inttCatDesc != null && thresholdBal != null && thresholdInttRate != null && minBal != null && maxBal != null && minWithdraw != null && maxWithdraw != null && drTxnFlag != null && dormancy != null && rowStatus != null && detailID != null) {
                        oDepositRateSlabBean = new DepositRateSlabBean();
                        oDepositRateSlabBean.setDep_product_id(depProdId);
                        oDepositRateSlabBean.setInttRateAmend(inttRateAmend);
                        oDepositRateSlabBean.setInttCapFreq(inttCapFreq);
                        oDepositRateSlabBean.setProdCode(prodCode);
                        oDepositRateSlabBean.setProdDesc(prodDesc);
                        oDepositRateSlabBean.setInttCat(inttCat);
                        oDepositRateSlabBean.setInttCatDesc(inttCatDesc);
                        oDepositRateSlabBean.setThresholdBal(thresholdBal);
                        oDepositRateSlabBean.setThresholdInttRate(thresholdInttRate);
                        oDepositRateSlabBean.setMinBal(minBal);
                        oDepositRateSlabBean.setMaxBal(maxBal);
                        oDepositRateSlabBean.setMinWithdraw(minWithdraw);
                        oDepositRateSlabBean.setMaxWithdraw(maxWithdraw);
                        oDepositRateSlabBean.setDrTxnFlag(drTxnFlag);
                        oDepositRateSlabBean.setDormancy(dormancy);
                        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.");
                }
            }            

            if (alDepositRateSlabBeanUpdated.size() > 0) {
                                        
                try {
                    con = DbHandler.getDBConnection();
                    con.setAutoCommit(false);
                    try {
                        proc = con.prepareCall("{ call operations2.upsert_sb_rate_slab(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       System.out.println("Error occurred during processing.");
                    }

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


                        proc.setString(1, oDepositRateSlabBean.getDep_product_id());
                        proc.setString(2, oDepositRateSlabBean.getInttRateAmend());
                        proc.setString(3, oDepositRateSlabBean.getThresholdBal());
                        proc.setString(4, oDepositRateSlabBean.getThresholdInttRate());
                        proc.setString(5, oDepositRateSlabBean.getMinBal());
                        proc.setString(6, oDepositRateSlabBean.getMaxBal());
                        proc.setString(7, oDepositRateSlabBean.getMinWithdraw());
                        proc.setString(8, oDepositRateSlabBean.getMaxWithdraw());
                        proc.setString(9, oDepositRateSlabBean.getInttCapFreq());
                        proc.setString(10, oDepositRateSlabBean.getDrTxnFlag());
                        proc.setString(11, oDepositRateSlabBean.getDormancy());
                        proc.setString(12, "Update");
                        proc.setString(13, pacsId);
                        proc.setString(14, tellerId);
                        proc.registerOutParameter(15, java.sql.Types.VARCHAR);

                        proc.execute();
                       // message = proc.getString(15);
                        if (!message.equalsIgnoreCase("SB rate slab successfully updated")) {
                            con.rollback();
                            break;
                        }
                    }
                    con.commit();
                  // message = proc.getString(15);                                       
                } catch (SQLException ex) {
                   System.out.println("Error occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       System.out.println("Error occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       System.out.println("Error occurred during connection close.");
                    }
                }            
            }   
            request.setAttribute("message", message);
            request.getRequestDispatcher("/Deposit/SBRateSlab.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>
}
