/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DataEntryBean.LoanAccountCreationBean;
import DataEntryBean.NscDetailsBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.sql.BatchUpdateException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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 javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author Tcs Helpdesk10
 */
public class LoanAccountCreationServlet extends HttpServlet {

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

    /**
     * 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 {

        HttpSession session = request.getSession(false);
        Connection con = null;
        CallableStatement proc = null;
        String message = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
        String collType = "";
        CallableStatement stmt = null;
        NscDetailsBean oNscDetailsBean = null;
        String qno = "";
        String nscMessage = "";
        int counter = 0;
        ArrayList<NscDetailsBean> alNscDetailsBean = new ArrayList<NscDetailsBean>();
        //String ServletName = request.getParameter("handle_id");
        LoanAccountCreationBean oLoanAccountCreationBean = new LoanAccountCreationBean();
        try {
           // BeanUtils.populate(oLoanAccountCreationBean, request.getParameterMap());
            collType = request.getParameter("collateralType");
        } catch (IllegalAccessException ex) {
           System.out.println("Error occurred during processing.");
        } catch (InvocationTargetException ex) {
           System.out.println("Error occurred during processing.");
        }

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

            proc.setString(1, pacsId);
            proc.setString(2, oLoanAccountCreationBean.getProductCode());
            proc.setString(3, oLoanAccountCreationBean.getInttCategory());
            proc.setString(4, oLoanAccountCreationBean.getCifNumber());
            proc.setString(5, oLoanAccountCreationBean.getLoanappAmt());
            proc.setString(6, oLoanAccountCreationBean.getLoanTerm());
            proc.setString(7, oLoanAccountCreationBean.getSegmentCode());
            proc.setString(8, user);
            proc.setString(9, oLoanAccountCreationBean.getActivityCode());
            proc.setString(10, oLoanAccountCreationBean.getSchemeCode());
            proc.setString(11, oLoanAccountCreationBean.getPurposeCode());
            proc.setString(12, oLoanAccountCreationBean.getCollateralType());
            proc.setString(13, oLoanAccountCreationBean.getDescription());
            proc.setString(14, oLoanAccountCreationBean.getCurrentValuation());
            proc.setString(15, oLoanAccountCreationBean.getSafeLendingMargin());
            proc.setString(16, oLoanAccountCreationBean.getGuarantorAddress());
            proc.setString(17, oLoanAccountCreationBean.getGuarantorDOB());
            proc.setString(18, oLoanAccountCreationBean.getGuarantorJob());
            proc.setString(19, oLoanAccountCreationBean.getGurantorIncome());
            proc.setString(20, oLoanAccountCreationBean.getGurantorName());
            proc.setString(21, oLoanAccountCreationBean.getEligAmt());
            proc.setString(22, oLoanAccountCreationBean.getGuarRelation());
            proc.setString(23, oLoanAccountCreationBean.getGuarIdType());
            proc.setString(24, oLoanAccountCreationBean.getGuarIdNo());
            proc.setString(26, oLoanAccountCreationBean.getDep_acc_no());
            proc.setString(27, oLoanAccountCreationBean.getExpDt());
            proc.setString(28, oLoanAccountCreationBean.getIntRate());
            proc.setString(29, oLoanAccountCreationBean.getPenIntRate());

            proc.registerOutParameter(25, java.sql.Types.VARCHAR);

            proc.execute();

           // message = proc.getString(25);

            if (message.contains("Operation sent for authorization with Ref No. #") ) 
            { 
                if (message.contains("#") && collType!=null && collType.equalsIgnoreCase("K")) {
                    qno = message.substring(message.indexOf("#") + 1);
                    counter = Integer.parseInt(request.getParameter("rowCounter"));
                    for (int i = 1; i <= counter; i++) {
                        try {

                       // String refno = request.getParameter("ref" + i);
                       // String amt = request.getParameter("amt" + i);
                       // String openDt = request.getParameter("openDt" + i);
                      //  String expDt = request.getParameter("expDt" + i);

                        if (refno != null) {
                            oNscDetailsBean = new NscDetailsBean();
                            oNscDetailsBean.setRefno(refno);
                            oNscDetailsBean.setAmt(amt);
                            oNscDetailsBean.setOpenDt(openDt);
                            oNscDetailsBean.setExpDt(expDt);
                            alNscDetailsBean.add(oNscDetailsBean);
                        }
                    } catch (Exception e) {
                        System.out.println("Error occurred during processing.");
                    }
                }

                if (alNscDetailsBean.size() > 0) {
                    try {

                        for (int j = 0; j < alNscDetailsBean.size(); j++) {
                            stmt = con.prepareCall("{ call Operations.saveNscDetails(?,?,?,?,?,?) }");
                            oNscDetailsBean = alNscDetailsBean.get(j);
                            stmt.setString(1, qno);
                            stmt.setString(2, oNscDetailsBean.getRefno());
                            stmt.setString(3, oNscDetailsBean.getAmt());
                            stmt.setString(4, oNscDetailsBean.getOpenDt());
                            stmt.setString(5, oNscDetailsBean.getExpDt());
                            stmt.registerOutParameter(6, java.sql.Types.VARCHAR);
                            stmt.execute();
                           // nscMessage = stmt.getString(6);

                            if (!nscMessage.equalsIgnoreCase("NSC Details inserted")) {
                                con.rollback();
                                message = nscMessage;
                                break;
                            }

                            stmt.close();
                        }

                        if (nscMessage.equalsIgnoreCase("NSC Details inserted")) {
                            con.commit();
                        }
                    } catch (BatchUpdateException ex) {
                        try {
                            con.rollback();
                            message = "Entered NSC details already tagged";
                        } catch (SQLException ex1) {
                           // Logger.getLogger(LoanAccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                           System.out.println("Error occurred during processing.");
                        }


                       // Logger.getLogger(LoanAccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error occurred during processing.");
                    } catch (SQLException ex1) {
                        try {
                            con.rollback();
                        } catch (SQLException e) {
                           // Logger.getLogger(LoanAccountCreationServlet.class.getName()).log(Level.SEVERE, null, e);
                           System.out.println("Error occurred during processing.");
                        }
                        message = "Error occurred while saving NSC details. Please try Again!";
                       // Logger.getLogger(LoanAccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex1);
                       System.out.println("Error occurred during processing.");
                    } finally {
                        try {
                            stmt.close();
                        } catch (SQLException e) {
                           // System.out.println(e.toString());
                           System.out.println("Error occurred during stmt close.");
                        }
                        try {
                            con.commit();
                            con.close();
                        } catch (SQLException ex) {
                           // Logger.getLogger(LoanAccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                           // System.out.println(ex.toString());
                           System.out.println("Error occurred during connection close.");
                        }
                    }

                }
            } else if (message.contains("#") && collType!=null && collType.equalsIgnoreCase("G")) {
                qno = message.substring(message.indexOf("#") + 1);
                counter = Integer.parseInt(request.getParameter("rowCounter"));
                for (int i = 1; i <= counter; i++) {
                    try {

                       // String bond = request.getParameter("bond" + i);
                       // String grossW = request.getParameter("grossW" + i);
                       // String netW = request.getParameter("netW" + i);

                        if (bond != null) {
                            oNscDetailsBean = new NscDetailsBean();
                            oNscDetailsBean.setBond(bond);
                            oNscDetailsBean.setGrossW(grossW);
                            oNscDetailsBean.setNetW(netW);
                            alNscDetailsBean.add(oNscDetailsBean);
                        }
                    } catch (Exception e) {
                        System.out.println("Error occurred during processing.");
                    }
                }

                if (alNscDetailsBean.size() > 0) {
                    try {

                        for (int j = 0; j < alNscDetailsBean.size(); j++) {
                            stmt = con.prepareCall("{ call Operations.saveGoldDetails(?,?,?,?,?) }");
                            oNscDetailsBean = alNscDetailsBean.get(j);
                            stmt.setString(1, qno);
                            stmt.setString(2, oNscDetailsBean.getBond());
                            stmt.setString(3, oNscDetailsBean.getGrossW());
                            stmt.setString(4, oNscDetailsBean.getNetW());
                            stmt.registerOutParameter(5, java.sql.Types.VARCHAR);
                            stmt.execute();
                           // nscMessage = stmt.getString(5);

                            if (!nscMessage.equalsIgnoreCase("Gold Details inserted")) {
                                con.rollback();
                                message = nscMessage;
                                break;
                            }
                            stmt.close();
                        }

                        if (nscMessage.equalsIgnoreCase("Gold Details inserted")) {
                            con.commit();
                        }
                    } catch (BatchUpdateException ex) {
                        try {
                            con.rollback();
                            message = "Entered Gold details already tagged";
                        } catch (SQLException ex1) {
                           System.out.println("Error occurred during processing.");
                        }

                       System.out.println("Error occurred during processing.");
                    } catch (SQLException ex1) {
                        try {
                            con.rollback();
                        } catch (SQLException e) {
                           System.out.println("Error occurred during processing.");
                        }
                        message = "Error occurred while saving Gold details. Please try Again!";
                       System.out.println("Error occurred during processing.");
                    } finally {
                        try {
                            stmt.close();
                        } catch (SQLException e) {
                           System.out.println("Error occurred during stmt close.");
                        }
                        try {
                            con.commit();
                            con.close();
                        } catch (SQLException ex) {
                           System.out.println("Error occurred during connection close.");
                        }
                    }
                }
            }
        }   

        } catch (SQLException ex) {
           // Logger.getLogger(LoanAccountCreationServlet.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.commit();
                con.close();
            } catch (SQLException ex) {
               // Logger.getLogger(LoanAccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               // System.out.println(ex.toString());
               System.out.println("Error occurred during connection close.");
            }

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

        }


    }

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