/*
 * 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 java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import DataEntryBean.mocProcessingBean;
import java.sql.BatchUpdateException;

/**
 *
 * @author 981898
 */
public class mocOperationsServlet 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;
        mocProcessingBean oMocProcessingBean;
        ArrayList<mocProcessingBean> alMocProcessingBean = new ArrayList<mocProcessingBean>();

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


            for (int i = 1; i <= counter; i++) {
                try {
                    oMocProcessingBean = new mocProcessingBean();
                   // oMocProcessingBean.setAccNo(request.getParameter("accNo" + i));
                   // oMocProcessingBean.setTxnAmt(request.getParameter("txnAmt" + i));
                   // oMocProcessingBean.setTxnInd(request.getParameter("txnInd" + i));
                  //  oMocProcessingBean.setSec_acc_no(request.getParameter("secAccNo"+i));
                  //  oMocProcessingBean.setNarration(request.getParameter("txnNarration" + i));

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

            }

            if (alMocProcessingBean.size() > 0) {
                try {
                    con = DbHandler.getDBConnection();
                    con.setAutoCommit(false);
                    proc = con.createStatement();
                    //ResultSet rs = proc.executeQuery("select MOC_TXN_DETAILS_SEQ.NEXTVAL from dual");
                    while (rs.next()) {
                        batchID = rs.getString(1);
                    }
                    proc.close();
                    for (int j = 0; j < alMocProcessingBean.size(); j++) {
                        stmt = con.prepareCall("{ call moc_txn_entry(?,?,?,?,?,?,?,?,?) }");
                        oMocProcessingBean = alMocProcessingBean.get(j);
                        stmt.setString(1, oMocProcessingBean.getAccNo());
                        stmt.setString(2, oMocProcessingBean.getTxnAmt());
                        stmt.setString(3, oMocProcessingBean.getTxnInd());
                        stmt.setString(4, oMocProcessingBean.getSec_acc_no());
                        stmt.setString(5, oMocProcessingBean.getNarration());
                        stmt.setString(6, pacsId);
                        stmt.setString(7, batchID);
                        stmt.setString(8, user);
                        stmt.registerOutParameter(9, java.sql.Types.VARCHAR);
                        //stmt.addBatch();
                        stmt.execute();
                       // message = stmt.getString(9);
                        if (!message.equalsIgnoreCase("MOC transaction details saved successfully")) {
                            con.rollback();
                            break;
                        }
                        stmt.close();
                    }
                    if (message.equalsIgnoreCase("MOC transaction details saved successfully")) {
                        message = message + " with MOC ID: " + 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/mocOperations.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 m.accno1,m.txn_ind,m.txn_amt,m.accno2,m.status,nvl(m.ref_no,'NA'),m.narration from moc_posting_dtl m where m.batch_id = '" + batchID + "' and m.status='ACTIVE' and m.pacs_id = '" + pacsId + "' ");

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

                    alMocProcessingBean.add(oMocProcessingBean);
                    SeachFound = 1;
                }
                if (alMocProcessingBean.size() > 0) {
                    request.setAttribute("alMocProcessingBean", alMocProcessingBean);
                    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/mocOperations.jsp").forward(request, response);
        }

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

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