package Controller;

import DataEntryBean.LoanProductCreationBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author Tcs Helpdesk10
 */
public class LoanProductCreationServlet 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 {
        Connection con = null;
        CallableStatement proc = null;
        String message = "";

        //String ServletName = request.getParameter("handle_id");

        LoanProductCreationBean oLoanProductCreationBean = new LoanProductCreationBean();

        if ("Create".equalsIgnoreCase(ServletName)) {

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

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

                proc.setString(1, oLoanProductCreationBean.getProductcode());
                proc.setString(2, oLoanProductCreationBean.getInttcategory());
                proc.setString(3, oLoanProductCreationBean.getProductname());
                proc.setString(4, oLoanProductCreationBean.getProductdescription());
                proc.setString(5, oLoanProductCreationBean.getIntcatdescription());
                proc.setString(6, oLoanProductCreationBean.getSegmentCode());
                proc.setString(7, "0"); //null glCode
                proc.setString(8, oLoanProductCreationBean.getStatus());
                proc.setString(9, oLoanProductCreationBean.getIntrate());
                proc.setString(10, oLoanProductCreationBean.getInttfrequency());
                proc.setString(11, oLoanProductCreationBean.getInttmethod());
                proc.setString(12, oLoanProductCreationBean.getInttcapfrequency());
                proc.setString(13, oLoanProductCreationBean.getInt_app_method());
                proc.setString(14, oLoanProductCreationBean.getPen_intt_rt());
                proc.setString(15, oLoanProductCreationBean.getPen_intt_method());
                proc.setString(16, oLoanProductCreationBean.getPen_inttcapfrequency());
                proc.setString(17, null);
                proc.setString(18, oLoanProductCreationBean.getMinDisbrs());
                proc.setString(19, oLoanProductCreationBean.getMaxDisbrs());
                proc.setString(20, oLoanProductCreationBean.getMinRepay());
                proc.setString(21, oLoanProductCreationBean.getMaxRepay());
                proc.setString(22, oLoanProductCreationBean.getMinTerm());
                proc.setString(23, oLoanProductCreationBean.getMaxTerm());
                proc.setString(24, oLoanProductCreationBean.getMinSancAmt());
                proc.setString(25, oLoanProductCreationBean.getMaxSancAmt());
                proc.setString(26, oLoanProductCreationBean.getDebitComp1());
                proc.setString(27, oLoanProductCreationBean.getDebitComp2());
                proc.setString(28, oLoanProductCreationBean.getEffectDate());
                proc.setString(29, oLoanProductCreationBean.getPenGracePr());
                proc.setString(30, oLoanProductCreationBean.getSecurity());
                proc.setString(31, oLoanProductCreationBean.getGuarantor());
                proc.setString(32, oLoanProductCreationBean.getRepayFrequency());
                proc.setString(33, ServletName);
                proc.setString(34, oLoanProductCreationBean.getLoanType());
                proc.setString(35, oLoanProductCreationBean.getGlCodeInttReceivable());
                proc.setString(36, oLoanProductCreationBean.getGlCodeInttReceived());
                proc.setString(37, oLoanProductCreationBean.getHeadAccType());
                proc.registerOutParameter(38, java.sql.Types.VARCHAR);

                proc.execute();

               // message = proc.getString(38);

            } catch (SQLException ex) {
                try {
                   // con.rollback();
                   // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                } catch (Exception ex1) {
                   // Logger.getLogger(LoanProductCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                   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) {
                   // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }

                request.setAttribute("message", message);
                request.getRequestDispatcher("/Loan/LoanProductCreation.jsp").forward(request, response);

            }

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

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

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

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

               // ResultSet rs = statement.executeQuery("select id,prod_code,int_cat,prod_name,prod_desc, intt_cat_desc,segment_code, gl_prod_id, status, intt_rate, intt_freq,  int_method, int_cap_freq,"
                        + "int_app_method,  min_sanc_amt,  max_sanc_amt, to_char(effec_dt,'dd/mm/yyyy') as effec_dt, pen_int_rate, pen_intt_freq, pen_int_method, pen_grace_period,"
                        + "debit_comp1, debit_comp2, max_disb, min_disb, max_rep,  min_rep,  max_term, min_term,GUARANTOR,SECURITY,repay_freq,LOAN_TYPE,GL_ID_INTT_RCVBL,GL_ID_INTT_RCVD,head_acc_type "
                        + " from loan_product dp"
                        + " where  int_cat= '" + oLoanProductCreationBean.getIntcatSearch() + "' AND prod_code='" + oLoanProductCreationBean.getProductcodeSearch() + "'");

                while (rs.next()) {

                    oLoanProductCreationBean.setLoanPd_id(rs.getString("id"));
                    oLoanProductCreationBean.setProductcode(rs.getString("prod_code"));
                    oLoanProductCreationBean.setInttcategory(rs.getString("int_cat"));
                    oLoanProductCreationBean.setProductname(rs.getString("prod_name"));
                    oLoanProductCreationBean.setProductdescription(rs.getString("prod_desc"));
                    oLoanProductCreationBean.setIntcatdescription(rs.getString("intt_cat_desc"));
                    oLoanProductCreationBean.setSegmentCode(rs.getString("segment_code"));
                    oLoanProductCreationBean.setGlCode(rs.getString("gl_prod_id"));
                    oLoanProductCreationBean.setStatus(rs.getString("status"));
                    oLoanProductCreationBean.setIntrate(rs.getString("intt_rate"));
                    oLoanProductCreationBean.setInttfrequency(rs.getString("intt_freq"));
                    oLoanProductCreationBean.setInttmethod(rs.getString("int_method"));
                    oLoanProductCreationBean.setInttcapfrequency(rs.getString("INT_CAP_FREQ"));
                    oLoanProductCreationBean.setInt_app_method(rs.getString("int_app_method"));
                    oLoanProductCreationBean.setMinSancAmt(rs.getString("min_sanc_amt"));
                    oLoanProductCreationBean.setMaxSancAmt(rs.getString("max_sanc_amt"));
                    oLoanProductCreationBean.setEffectDate(rs.getString("effec_dt"));
                    oLoanProductCreationBean.setPen_intt_rt(rs.getString("pen_int_rate"));
                    oLoanProductCreationBean.setPen_inttcapfrequency(rs.getString("pen_intt_freq"));
                    oLoanProductCreationBean.setPen_intt_method(rs.getString("pen_int_method"));
                    oLoanProductCreationBean.setPenGracePr(rs.getString("pen_grace_period"));
                    oLoanProductCreationBean.setMaxDisbrs(rs.getString("max_disb"));
                    oLoanProductCreationBean.setMinDisbrs(rs.getString("min_disb"));
                    oLoanProductCreationBean.setMaxRepay(rs.getString("max_rep"));
                    oLoanProductCreationBean.setMinRepay(rs.getString("min_rep"));
                    oLoanProductCreationBean.setMaxTerm(rs.getString("max_term"));
                    oLoanProductCreationBean.setMinTerm(rs.getString("min_term"));
                    oLoanProductCreationBean.setDebitComp1(rs.getString("debit_comp1"));
                    oLoanProductCreationBean.setDebitComp2(rs.getString("debit_comp2"));
                    oLoanProductCreationBean.setGuarantor(rs.getString("GUARANTOR"));
                    oLoanProductCreationBean.setSecurity(rs.getString("SECURITY"));
                    oLoanProductCreationBean.setRepayFrequency(rs.getString("repay_freq"));
                    oLoanProductCreationBean.setLoanType(rs.getString("LOAN_TYPE"));
                    oLoanProductCreationBean.setGlCodeInttReceivable(rs.getString("GL_ID_INTT_RCVBL"));
                    oLoanProductCreationBean.setGlCodeInttReceived(rs.getString("GL_ID_INTT_RCVD"));
                    oLoanProductCreationBean.setHeadAccType(rs.getString("head_acc_type"));

                    SeachFound = 1;
                    request.setAttribute("displayFlag", "Y");
                }
               // statement.close();
               // connection.close();

            } catch (SQLException ex) {

               // Logger.getLogger(LoanProductCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    if(statement !=null)
                        statement.close();
                    if (connection != null)
                    connection.close();

            } catch (Exception e) {               
               System.out.println("Error Occurred during connection close.");
            }

            }

            if (SeachFound == 0) {
                message = "Product Code or Interest Category not exists in the system";
                request.setAttribute("message", message);
            }

            request.setAttribute("oLoanProductCreationBeanObj", oLoanProductCreationBean);
            request.getRequestDispatcher("/Loan/LoanProductCreation.jsp").forward(request, response);

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

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

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

                proc.setString(1, oLoanProductCreationBean.getProductcodeAmend());
                proc.setString(2, oLoanProductCreationBean.getInttcategoryAmend());
                proc.setString(3, oLoanProductCreationBean.getProductnameAmend());
                proc.setString(4, oLoanProductCreationBean.getProductdescriptionAmend());
                proc.setString(5, oLoanProductCreationBean.getIntcatdescriptionAmend());
                proc.setString(6, oLoanProductCreationBean.getSegmentCodeAmend());
                proc.setString(7, oLoanProductCreationBean.getGlCodeAmend());
                proc.setString(8, oLoanProductCreationBean.getStatusAmend());
                proc.setString(9, oLoanProductCreationBean.getIntrateAmend());
                proc.setString(10, oLoanProductCreationBean.getInttfrequencyAmend());
                proc.setString(11, oLoanProductCreationBean.getInttmethodAmend());
                proc.setString(12, oLoanProductCreationBean.getInttcapfrequencyAmend());
                proc.setString(13, oLoanProductCreationBean.getInt_app_methodAmend());
                proc.setString(14, oLoanProductCreationBean.getPen_intt_rtAmend());
                proc.setString(15, oLoanProductCreationBean.getPen_intt_methodAmend());
                proc.setString(16, oLoanProductCreationBean.getPen_inttcapfrequencyAmend());
                proc.setString(17, null);
                proc.setString(18, oLoanProductCreationBean.getMinDisbrsAmend());
                proc.setString(19, oLoanProductCreationBean.getMaxDisbrsAmend());
                proc.setString(20, oLoanProductCreationBean.getMinRepayAmend());
                proc.setString(21, oLoanProductCreationBean.getMaxRepayAmend());
                proc.setString(22, oLoanProductCreationBean.getMinTermAmend());
                proc.setString(23, oLoanProductCreationBean.getMaxTermAmend());
                proc.setString(24, oLoanProductCreationBean.getMinSancAmtAmend());
                proc.setString(25, oLoanProductCreationBean.getMaxSancAmtAmend());
                proc.setString(26, oLoanProductCreationBean.getDebitComp1Amend());
                proc.setString(27, oLoanProductCreationBean.getDebitComp2Amend());
                proc.setString(28, oLoanProductCreationBean.getEffectDateAmend());

                proc.setString(29, oLoanProductCreationBean.getPenGracePrAmend());
                proc.setString(30, oLoanProductCreationBean.getSecurityAmend());
                proc.setString(31, oLoanProductCreationBean.getGuarantorAmend());
                proc.setString(32, oLoanProductCreationBean.getRepayFrequencyAmend());
                proc.setString(33, ServletName);
                proc.setString(34, oLoanProductCreationBean.getLoanTypeAmend());
                proc.setString(35, oLoanProductCreationBean.getGlCodeInttReceivableAmend());
                proc.setString(36, oLoanProductCreationBean.getGlCodeInttReceivedAmend());
                proc.setString(37, oLoanProductCreationBean.getHeadAccTypeAmend());
                proc.registerOutParameter(38, java.sql.Types.VARCHAR);

                proc.execute();

               // message = proc.getString(38);

            } catch (SQLException ex) {
                try {
                   // con.rollback();
                } catch (Exception ex1) {
                   // Logger.getLogger(LoanProductCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                   System.out.println("Error occurred during processing.");
                }
               // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, 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) {
                   // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }

                request.setAttribute("message", message);
                request.getRequestDispatcher("/Loan/LoanProductCreation.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 {
        processRequest(request, response);
    }

    /**
     * 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 {
        processRequest(request, response);



    }

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