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

import DataEntryBean.VendorMasterDtlBean;
import DataEntryBean.VendorMasterHeaderBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.io.PrintWriter;
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.ArrayList;
import java.util.StringTokenizer;
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 986137
 */
public class VendorMasterServlet 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 {
    }

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

        Connection con = null;
        CallableStatement proc = null;
        String message = "";
        String ScreenStatus = "";
        String hdrID = "";
        HttpSession session = request.getSession(false);

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

        VendorMasterHeaderBean oVendorMasterHeaderBean = new VendorMasterHeaderBean();
         VendorMasterDtlBean oVendorMasterDtlBean = new VendorMasterDtlBean();
        oVendorMasterDtlBean = null;
        ArrayList<VendorMasterDtlBean> alVendorMasterDtlBean = new ArrayList<VendorMasterDtlBean>();



        //For Amend Div

        ArrayList<VendorMasterDtlBean> alVendorMasterDtlBeanNew = new ArrayList<VendorMasterDtlBean>();
        ArrayList<VendorMasterDtlBean> alVendorMasterDtlBeanDeleted = new ArrayList<VendorMasterDtlBean>();
        ArrayList<VendorMasterDtlBean> alVendorMasterDtlBeanUpdated = new ArrayList<VendorMasterDtlBean>();

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


            try {
              //  BeanUtils.populate(oVendorMasterHeaderBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               // Logger.getLogger(VendorMasterServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               // Logger.getLogger(VendorMasterServlet.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_vendor_hdr(?,?,?,?,?,?,?,?,?,?) }");
                } catch (SQLException ex) {
                   // Logger.getLogger(VendorMasterServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }

                proc.setString(1, oVendorMasterHeaderBean.getVendorID());
                proc.setString(2, oVendorMasterHeaderBean.getVendorname());
                proc.setString(3, oVendorMasterHeaderBean.getAddress());
                proc.setString(4, oVendorMasterHeaderBean.getPhone());
                proc.setString(5, oVendorMasterHeaderBean.getContactperson());
                proc.setString(6, ServletName);
                proc.setString(7, pacsId);
                proc.registerOutParameter(8, java.sql.Types.VARCHAR);
                proc.registerOutParameter(9, java.sql.Types.VARCHAR);
                proc.setString(10, oVendorMasterHeaderBean.getGstin());
                
                proc.execute();

               // message = proc.getString(8);
                hdrID = proc.getString(9);



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

            }
            int counter = Integer.parseInt(request.getParameter("rowCounter"));

            for (int i = 1; i <= counter; i++) {
                try {

                  //  String productId = request.getParameter("product_id" + i);


                    if (productId != null) {
                        oVendorMasterDtlBean = new VendorMasterDtlBean();
                        oVendorMasterDtlBean.setProduct_id(productId);
                        alVendorMasterDtlBean.add(oVendorMasterDtlBean);
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }
            if ((alVendorMasterDtlBean.size() > 0) && (!message.equalsIgnoreCase(""))) {

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


                    for (int j = 0; j < alVendorMasterDtlBean.size(); j++) {

                        oVendorMasterDtlBean = alVendorMasterDtlBean.get(j);


                        proc.setString(1, hdrID);
                        proc.setString(2, oVendorMasterDtlBean.getDetailID());
                        proc.setString(3, oVendorMasterDtlBean.getProduct_id());
                        proc.setString(4, ServletName);
                        proc.addBatch();


                    }

                    proc.executeBatch();

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

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

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

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

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

              //  ResultSet rs = statement.executeQuery("select t.id,t.name,t.address,t.phn_no,t.contact_prsn,gst_no from trading_vendor_mst t where id= '" + oVendorMasterHeaderBean.getVendorID() + "' ");

                while (rs.next()) {

                    oVendorMasterHeaderBean.setVendorID(rs.getString("id"));
                    oVendorMasterHeaderBean.setVendorname(rs.getString("name"));
                    oVendorMasterHeaderBean.setAddress(rs.getString("address"));
                    oVendorMasterHeaderBean.setPhone(rs.getString("phn_no"));
                    oVendorMasterHeaderBean.setContactperson(rs.getString("contact_prsn"));
                    oVendorMasterHeaderBean.setGstin(rs.getString("gst_no"));

                    SeachFound = 1;
                    request.setAttribute("displayFlag", "Y");

                }

                statement.close();


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

            if (SeachFound == 0) {
                message = "Vendor not exists in the system";
                request.setAttribute("message", message);
            }


            //For Details Part Populate

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

               // ResultSet rs = statement.executeQuery("select d.ID,m.comm_type, m.TYPE_DESC, m.comm_subtype, m.SUBTYPE_DESC,d.prod_id "
                        + " from trading_product_mst m,trading_vendor_dtl d"
                        + " where m.id=d.prod_id"
                        + " and d.vnd_mst_id= '" + oVendorMasterHeaderBean.getVendorID() + "' ");

                while (rs.next()) {

                    oVendorMasterDtlBean = new VendorMasterDtlBean();
                    oVendorMasterDtlBean.setDetailID(rs.getString("id"));
                    oVendorMasterDtlBean.setCommoditytype(rs.getString("comm_type"));
                    oVendorMasterDtlBean.setTypeDesc(rs.getString("TYPE_DESC"));
                    oVendorMasterDtlBean.setCommoditysubtype(rs.getString("comm_subtype"));
                    oVendorMasterDtlBean.setSubtypeDesc(rs.getString("SUBTYPE_DESC"));
                    oVendorMasterDtlBean.setProduct_id(rs.getString("prod_id"));

                    alVendorMasterDtlBean.add(oVendorMasterDtlBean);

                }

               // statement.close();
               // connection.close();

            } catch (SQLException ex) {
               // Logger.getLogger(VendorMasterServlet.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.");
            }

            }


            request.setAttribute("VendorMasterHeaderBeanObj", oVendorMasterHeaderBean);
            request.setAttribute("alVendorMasterDtlBean", alVendorMasterDtlBean);
            request.getRequestDispatcher("/Trading_JSP/VendorEnrollmentEnquiry.jsp").forward(request, response);

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



            String productId = null;
            String rowStatus = null;
            String detailID = null;
            String deletedRows = null;


            try {
               // BeanUtils.populate(oVendorMasterHeaderBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               // Logger.getLogger(VendorMasterServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               // Logger.getLogger(VendorMasterServlet.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_vendor_hdr(?,?,?,?,?,?,?,?,?,?) }");
                } catch (SQLException ex) {
                   // Logger.getLogger(VendorMasterServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }

                proc.setString(1, oVendorMasterHeaderBean.getVendorID());
                proc.setString(2, oVendorMasterHeaderBean.getVendornameAmend());
                proc.setString(3, oVendorMasterHeaderBean.getAddressAmend());
                proc.setString(4, oVendorMasterHeaderBean.getPhoneAmend());
                proc.setString(5, oVendorMasterHeaderBean.getContactpersonAmend());
                proc.setString(6, ServletName);
                proc.setString(7, pacsId);
                proc.registerOutParameter(8, java.sql.Types.VARCHAR);
                proc.registerOutParameter(9, java.sql.Types.VARCHAR);
                proc.setString(10, oVendorMasterHeaderBean.getGstinAmend());
                
                proc.execute();

              //  message = proc.getString(8);
                hdrID = proc.getString(9);



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

            }
            int counter = Integer.parseInt(request.getParameter("rowCounter"));

            for (int i = 1; i <= counter; i++) {
                try {

                  //  productId = request.getParameter("product_idAmend" + i);
                    rowStatus = request.getParameter("rowStatus" + i);
                  //  detailID = request.getParameter("detailIDAmend" + i);


                    if (productId != null && rowStatus != null) {
                        oVendorMasterDtlBean = new VendorMasterDtlBean();
                        oVendorMasterDtlBean.setProduct_id(productId);
                        oVendorMasterDtlBean.setDetailID(detailID);

                        if (rowStatus.equals("N")) {
                            alVendorMasterDtlBeanNew.add(oVendorMasterDtlBean);
                        } else {
                            alVendorMasterDtlBeanUpdated.add(oVendorMasterDtlBean);
                        }


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



            //For Deletion

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

            if ((!deletedRows.equalsIgnoreCase(null)) || (!deletedRows.equalsIgnoreCase(""))) {
                StringTokenizer tokenizer = new StringTokenizer(deletedRows, ",");

                while (tokenizer.hasMoreTokens()) {

                    oVendorMasterDtlBean = new VendorMasterDtlBean();
                    oVendorMasterDtlBean.setDetailID(tokenizer.nextToken());

                    alVendorMasterDtlBeanDeleted.add(oVendorMasterDtlBean);

                }
            }




            if ((alVendorMasterDtlBeanUpdated.size() > 0) && (!message.equalsIgnoreCase(""))) {

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


                    for (int j = 0; j < alVendorMasterDtlBeanUpdated.size(); j++) {

                        oVendorMasterDtlBean = new VendorMasterDtlBean();

                        oVendorMasterDtlBean = alVendorMasterDtlBeanUpdated.get(j);


                        proc.setString(1, hdrID);
                        proc.setString(2, oVendorMasterDtlBean.getDetailID());
                        proc.setString(3, oVendorMasterDtlBean.getProduct_id());
                        proc.setString(4, ServletName);
                        proc.addBatch();


                    }

                    proc.executeBatch();

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

            //for deletion

            if ((alVendorMasterDtlBeanDeleted.size() > 0) && (!message.equalsIgnoreCase(""))) {

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


                    for (int j = 0; j < alVendorMasterDtlBeanDeleted.size(); j++) {

                        oVendorMasterDtlBean = new VendorMasterDtlBean();

                        oVendorMasterDtlBean = alVendorMasterDtlBeanDeleted.get(j);


                        proc.setString(1, hdrID);
                        proc.setString(2, oVendorMasterDtlBean.getDetailID());
                        proc.setString(3, null);
                        proc.setString(4, "Delete");
                        proc.addBatch();


                    }

                    proc.executeBatch();

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


            //For New Insertion


            if ((alVendorMasterDtlBeanNew.size() > 0) && (!message.equalsIgnoreCase(""))) {

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


                    for (int j = 0; j < alVendorMasterDtlBeanNew.size(); j++) {

                        oVendorMasterDtlBean = new VendorMasterDtlBean();
                        oVendorMasterDtlBean = alVendorMasterDtlBeanNew.get(j);


                        proc.setString(1, hdrID);
                        proc.setString(2, oVendorMasterDtlBean.getDetailID());
                        proc.setString(3, oVendorMasterDtlBean.getProduct_id());
                        proc.setString(4, "Create");
                        proc.addBatch();


                    }

                    proc.executeBatch();

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