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

package Controller;

//import Dao.LienMarkingDao;
//import DataEntryBean.ChequeDetailsBean;
//import java.io.IOException;
//import java.util.ArrayList;
//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.LienMarkingBean;
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 1004242
 */
public class LienMarkingServlet extends HttpServlet{
  @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 lienType = "";
        CallableStatement stmt = null;
        NscDetailsBean oNscDetailsBean = null;
        String qno = "";
        String nscMessage = "";
        int counter = 0;
        ArrayList<NscDetailsBean> alNscDetailsBean = new ArrayList<NscDetailsBean>();
        LienMarkingBean oLienMarkingBean = new LienMarkingBean();
        try {
          // BeanUtils.populate(oLienMarkingBean, request.getParameterMap());
            lienType = request.getParameter("lienType");
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(LienMarkingServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(LienMarkingServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error occurred during processing.");           
        }

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

            proc.setString(1, oLienMarkingBean.getLoanAccount());
            proc.setString(2, oLienMarkingBean.getDep_acc_no());
            proc.setString(3, oLienMarkingBean.getKVPNo());
            proc.setString(4, oLienMarkingBean.getLienType());
            proc.setString(5, oLienMarkingBean.getCurrentValuation());
            proc.setString(6, oLienMarkingBean.getSafeLendingMargin());
            proc.setString(7, oLienMarkingBean.getDescription());
            proc.setString(8, oLienMarkingBean.getExpDt());
            proc.setString(9, oLienMarkingBean.getOpenDt());
            proc.setString(10, user);
            proc.setString(11, pacsId);

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

            proc.execute();

           // message = proc.getString(12);

            if (message.contains("Lien details Saved successfully Check Lien Report For Loan A/C #") ) 
            {    
                if (message.contains("#") && lienType!=null && lienType.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 Operations2.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(LienMarkingServlet.class.getName()).log(Level.SEVERE, null, ex1);
                           System.out.println("Error occurred during processing.");
                        }


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

                }
            } if (message.contains("#") && lienType!=null && lienType.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 Operations2.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) {
           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(LienMarkingServlet.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/LienMarking.jsp").forward(request, response);

        }
    }

//        HttpSession session = request.getSession(false);
//        String pacsId = (String) session.getAttribute("pacsId");
//        String tellerId = (String)session.getAttribute("user");
//        LienMarkingDao aiDao = new LienMarkingDao();
//        String result = null;
//
//
//        try{
//
//            String lienType = request.getParameter("lienType");
//            String KVPNo = request.getParameter("KVPNo");
//            String LoanAccount = request.getParameter("LoanAccount");
//            String DepAccount = request.getParameter("dep_acc_no");
//            String SecurityAmt = request.getParameter("currentValuation");
//            String safeLendingMargin = request.getParameter("safeLendingMargin");
//            String description = request.getParameter("description");
//            String Expdt = request.getParameter("expDt");
//            String OpenDt = request.getParameter("openDt");
//
//            result = aiDao.LienMarkingServletProc(LoanAccount, DepAccount, KVPNo, lienType, SecurityAmt, safeLendingMargin, description, Expdt, OpenDt, tellerId, pacsId);
//
//            request.setAttribute("message1", result);
//            request.getRequestDispatcher("/Deposit/LienMarking.jsp").forward(request, response);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            request.setAttribute("message1", "Error occured. Please try again");
//            request.getRequestDispatcher("/Deposit/LienMarking.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>
}
