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

import LoginDb.DbHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
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 DataEntryBean.BatchProcessingBean;
import java.sql.BatchUpdateException;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author 594267
 */
public class BatchTransactionServlet_old 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 {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet BatchTransactionServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet BatchTransactionServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

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

        HttpSession session = request.getSession(false);

        String message = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
        String handle_id = request.getParameter("handle_id");
        int counter = Integer.parseInt(request.getParameter("rowCounter"));
        String batchID = null;
        Connection con = null;
        Statement proc = null;
        Connection connection = null;
        CallableStatement stmt = null;
        BatchProcessingBean oBatchProcessingBean;
        ArrayList<BatchProcessingBean> alBatchProcessingBean = new ArrayList<BatchProcessingBean>();

        if ("create".equalsIgnoreCase(handle_id)) {


            for (int i = 1; i <= counter; i++) {
                try {
                    oBatchProcessingBean = new BatchProcessingBean();
                    //oBatchProcessingBean.setAccType(request.getParameter("accType" + i));
                   // oBatchProcessingBean.setAccNo(request.getParameter("accNo" + i));
                   // oBatchProcessingBean.setTxnAmt(request.getParameter("txnAmt" + i));
                   // oBatchProcessingBean.setTxnInd(request.getParameter("txnInd" + i));
                   // oBatchProcessingBean.setNarration(request.getParameter("txnNarration" + i));

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

            }

            if (alBatchProcessingBean.size() > 0) {
                try {
                    con = DbHandler.getDBConnection();
                    con.setAutoCommit(false);
                    proc = con.createStatement();
                    //ResultSet rs = proc.executeQuery("select batch_txn_details_seq.NEXTVAL from dual");
                    while (rs.next()) {
                        batchID = rs.getString(1);
                    }
                    proc.close();
                    for (int j = 0; j < alBatchProcessingBean.size(); j++) {
                        stmt = con.prepareCall("{ call batch_txn_entry(?,?,?,?,?,?,?,?) }");
                        oBatchProcessingBean = alBatchProcessingBean.get(j);
                        stmt.setString(1, oBatchProcessingBean.getAccType());
                        stmt.setString(2, oBatchProcessingBean.getAccNo());
                        stmt.setString(3, oBatchProcessingBean.getTxnAmt());
                        stmt.setString(4, oBatchProcessingBean.getTxnInd());
                        stmt.setString(5, oBatchProcessingBean.getNarration());
                        stmt.setString(6, pacsId);
                        stmt.setString(7, batchID);
                        stmt.registerOutParameter(8, java.sql.Types.VARCHAR);
                        //stmt.addBatch();
                        stmt.execute();
                       // message = stmt.getString(8);
                        if (!message.equalsIgnoreCase("Batch transaction details saved successfully")) {
                            con.rollback();
                            break;
                        }
                        stmt.close();
                    }
                    if (message.equalsIgnoreCase("Batch transaction details saved successfully")) {
                        message = message + " with batchID: " + batchID;
                        con.commit();
                    }
                    //message = "Batch details saved successfully";
                /*message = stmt.getString(6);
                    if(!message.equalsIgnoreCase("Batch transaction details saved successfully")){
                    con.rollback();
                    }*/

                } catch (BatchUpdateException ex) {

                    try {
                        con.rollback();

                        //SuccessFlag = BatchExecutionFailedOperationObject.BatchExecutionFailedOperation("DepositKYCCreation.jsp", hdrId);
                    /*if(!stmt.getString(6).isEmpty())
                        message = stmt.getString(6);
                        else*/
                        message = "Error in savings batch details";
                        // message = ex.toString();


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


                   // Logger.getLogger(DepositKYCCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error occurred during processing.");
                } catch (SQLException ex1) {
                   // message = "Error occurred in saving batch details. Please try Again!";
                   // Logger.getLogger(DepositKYCCreationServlet.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());
//                }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(DepositKYCCreationServlet.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("/Deposit/BatchTransaction.jsp").forward(request, response);
        }
        if ("search".equalsIgnoreCase(handle_id)) {

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

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

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

            try {

               // resultset = statement.executeQuery("select b.acct_type,decode(b.acct_type, 'G', b.gl_ac_no,'L',b.loan_ac_no, b.dep_ac_no) acc_no, b.txn_ind,b.txn_amt,decode(b.status,'ACTIVE','Transaction not yet posted','INACTIVE','Transaction posted'),nvl(b.txn_ref_no,'NA'),b.narration,b.loan_ac_no from batch_txn_details b where b.batch_id ='" + batchID + "' and b.pacs_id = '" + pacsId + "'");

                while (resultset.next()) {
                    oBatchProcessingBean = new BatchProcessingBean();
                    oBatchProcessingBean.setAccType(resultset.getString(1));
                    oBatchProcessingBean.setAccNo(resultset.getString(2));
                    oBatchProcessingBean.setTxnInd(resultset.getString(3));
                    oBatchProcessingBean.setTxnAmt(resultset.getString(4));
                    oBatchProcessingBean.setTxnStatus(resultset.getString(5));
                    oBatchProcessingBean.setTxnRefNo(resultset.getString(6));
                    oBatchProcessingBean.setNarration(resultset.getString(7));

                    if(resultset.getString(8)!=null)
                    {
                        oBatchProcessingBean.setAccNo(resultset.getString(8));
                    }
                    alBatchProcessingBean.add(oBatchProcessingBean);
                    SeachFound = 1;
                }
                if (alBatchProcessingBean.size() > 0) {
                    request.setAttribute("alBatchProcessingBean", alBatchProcessingBean);
                    request.setAttribute("message", "");
                    request.setAttribute("handle_id", "S");
                    request.setAttribute("batchID", batchID);
                }
                //request.setAttribute("displayFlag", "Y");


            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    statement.close();
                    connection.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(BatchTransactionServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }
            }
            if (SeachFound == 0) {
                message = "BatchID " + batchID + " not found";
                request.setAttribute("message", message);
            }

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

        if ("execute".equalsIgnoreCase(handle_id)) {
           // batchID = request.getParameter("batchID");
            try {
                connection = DbHandler.getDBConnection();
                connection.setAutoCommit(false);
                stmt = connection.prepareCall("{ call execute_batch_txn(?,?,?) }");
                stmt.setString(1, batchID);
                stmt.setString(2, pacsId);
                stmt.registerOutParameter(3, java.sql.Types.VARCHAR);
                //stmt.addBatch();
                stmt.execute();
               // message = stmt.getString(3);
                if (message.equalsIgnoreCase("Batch transaction successfully posted")) {

                    connection.commit();
                } else {
                    connection.rollback();
                }
                request.setAttribute("message", message);
            } catch (SQLException ex) {
               // Logger.getLogger(BatchTransactionServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    connection.close();
                    stmt.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(BatchTransactionServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }
            }
            request.getRequestDispatcher("/Deposit/BatchTransaction.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>
}
