/*
 * 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.TrandinStockRegisterBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
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 oracle.jdbc.OracleTypes;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
//import com.itextpdf.text.BaseColor;
//import com.itextpdf.text.Document;
//import com.itextpdf.text.DocumentException;
//import com.itextpdf.text.Rectangle;
//import com.itextpdf.text.pdf.Barcode;
//import com.itextpdf.text.pdf.Barcode128;
//import com.itextpdf.text.pdf.PdfPCell;
//import com.itextpdf.text.pdf.PdfPTable;
//import com.itextpdf.text.pdf.PdfWriter;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.servlet.ServletOutputStream;



/**
 *
 * @author Tcs Help desk122
 */
public class TradingStockRegisterServlet 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
     */

    private static final String FILE_NAME = "/barcode"+System.currentTimeMillis()+".pdf";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        Connection con = null;
        CallableStatement proc = null;
        ResultSet rs = null;
        int searchFound = 0;
        String message = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
        String ServletName = request.getParameter("handle_id");
        ServletOutputStream stream = null;
        BufferedInputStream buf = null;

        TrandinStockRegisterBean oTrandinStockRegisterBean = new TrandinStockRegisterBean();

        ArrayList<TrandinStockRegisterBean> alTrandinStockRegisterBean = new ArrayList<TrandinStockRegisterBean>();

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

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

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

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

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

                    if (purchaseId != null) {
                        oTrandinStockRegisterBean = new TrandinStockRegisterBean();
                        oTrandinStockRegisterBean.setPurchase_id(purchaseId);
                        oTrandinStockRegisterBean.setProduct_id(productId);
                       // oTrandinStockRegisterBean.setStkexpiryDate(request.getParameter("stkexpiryDate" + i));
                        //oTrandinStockRegisterBean.setSelectperish(request.getParameter("selectperish" + i));
                        //oTrandinStockRegisterBean.setPrice_unit(request.getParameter("price_unit" + i));
                        //oTrandinStockRegisterBean.setQuantity(request.getParameter("quantity" + i));
                        //oTrandinStockRegisterBean.setPfnm(request.getParameter("pfnm" + i));
                        //oTrandinStockRegisterBean.setGodown_id(request.getParameter("godown_id" + i));
                        //oTrandinStockRegisterBean.setStockdesc(request.getParameter("stockdesc" + i));
                        //oTrandinStockRegisterBean.setPfm(request.getParameter("pfm" + i));
                        alTrandinStockRegisterBean.add(oTrandinStockRegisterBean);
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }
            //int p = alTrandinStockRegisterBean.size();
            if ((alTrandinStockRegisterBean.size() > 0)) {

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

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

                        oTrandinStockRegisterBean = alTrandinStockRegisterBean.get(j);
                        proc.setString(1, oTrandinStockRegisterBean.getProduct_id());
                        proc.setString(2, oTrandinStockRegisterBean.getPurchase_id());
                        proc.setString(3, pacsId);
                        proc.setString(4, oTrandinStockRegisterBean.getStkexpiryDate());
                        proc.setString(5, oTrandinStockRegisterBean.getSelectperish());
                        proc.setString(6, oTrandinStockRegisterBean.getPrice_unit());
                        proc.setString(7, oTrandinStockRegisterBean.getQuantity());
                        proc.setString(8, oTrandinStockRegisterBean.getPfnm());
                        proc.setString(9, oTrandinStockRegisterBean.getGodown_id());
                        proc.setString(10, oTrandinStockRegisterBean.getStockdesc());
                        proc.setString(11, oTrandinStockRegisterBean.getPfm());

                        proc.addBatch();
                    }

                    proc.executeBatch();
                    message = "Data inserted successfully!!";
                } catch (SQLException ex) {
                   // Logger.getLogger(TradingStockRegisterServlet.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(TradingStockRegisterServlet.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/TradingStockRegister.jsp").forward(request, response);
        
        } else if ("Viewstock".equalsIgnoreCase(ServletName)) {
            
            oTrandinStockRegisterBean = new TrandinStockRegisterBean();

            alTrandinStockRegisterBean = new ArrayList<TrandinStockRegisterBean>();
            try {
              //  BeanUtils.populate(oTrandinStockRegisterBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               // Logger.getLogger(TradingStockRegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               // Logger.getLogger(TradingStockRegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            }
            try {
                con = DbHandler.getDBConnection();
                try {
                    proc = con.prepareCall("{ call TRADING_OPERATION.trading_View_Stock_register(?,?,?,?,?,?) }");
                } catch (SQLException ex) {
                   // Logger.getLogger(TradingStockRegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }
                proc.setString(1, oTrandinStockRegisterBean.getCommoditytypeSearch());
                proc.setString(2, oTrandinStockRegisterBean.getCommoditySubtypeSearch());
                proc.setString(3, oTrandinStockRegisterBean.getVendor_id());
                proc.setString(4, pacsId);

                proc.registerOutParameter(5, OracleTypes.CURSOR);
                proc.registerOutParameter(6, java.sql.Types.VARCHAR);

                proc.executeUpdate();
               // message = proc.getString(6);

               // rs = (ResultSet) proc.getObject(5);

                while (rs.next()) {
                    searchFound = 1;
                    oTrandinStockRegisterBean = new TrandinStockRegisterBean();
                    oTrandinStockRegisterBean.setStock_id(rs.getString(1));
                    oTrandinStockRegisterBean.setName(rs.getString(2));
                    oTrandinStockRegisterBean.setCommoditytype(rs.getString(3));
                    oTrandinStockRegisterBean.setCommoditysubtype(rs.getString(4));
                    oTrandinStockRegisterBean.setEntDate(rs.getString(5));
                    oTrandinStockRegisterBean.setSelectperish(rs.getString(6));
                    oTrandinStockRegisterBean.setStkexpiryDate(rs.getString(7));
                    oTrandinStockRegisterBean.setPrice_unit(rs.getString(8));
                    oTrandinStockRegisterBean.setQuantity(rs.getString(9));
                    oTrandinStockRegisterBean.setQuantity_availed(rs.getString(10));
                    oTrandinStockRegisterBean.setQuantity_available(rs.getString(11));
                    oTrandinStockRegisterBean.setPfnm(rs.getString(12));
                    oTrandinStockRegisterBean.setPfm(rs.getString(13));                    

                    alTrandinStockRegisterBean.add(oTrandinStockRegisterBean);
                    request.setAttribute("displayFlag", "Y");

                }
            } catch (SQLException ex) {
               // Logger.getLogger(TradingStockRegisterServlet.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(TradingStockRegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }
            }
            if (searchFound == 0) {
                message = "No data exists for selected item";
                request.setAttribute("message", message);
            }            
            request.setAttribute("oTrandinStockRegisterBean", oTrandinStockRegisterBean);
            request.setAttribute("arrTrandinStockRegisterBean", alTrandinStockRegisterBean);
            request.setAttribute("message", message);

            request.getRequestDispatcher("/Trading_JSP/TradingStockRegister.jsp").forward(request, response);

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

            oTrandinStockRegisterBean = new TrandinStockRegisterBean();

            alTrandinStockRegisterBean = new ArrayList<TrandinStockRegisterBean>();
            try {
               // BeanUtils.populate(oTrandinStockRegisterBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               System.out.println("Error occurred during processing.");
            }
            try {
                con = DbHandler.getDBConnection();
                try {
                    proc = con.prepareCall("{ call TRADING_OPERATION.trading_edit_Stock_register(?,?,?,?,?,?) }");
                } catch (SQLException ex) {
                   System.out.println("Error occurred during processing.");
                }
                proc.setString(1, oTrandinStockRegisterBean.getCommoditytypeSearch());
                proc.setString(2, oTrandinStockRegisterBean.getCommoditySubtypeSearch());
                proc.setString(3, oTrandinStockRegisterBean.getVendor_id());
                proc.setString(4, pacsId);

                proc.registerOutParameter(5, OracleTypes.CURSOR);
                proc.registerOutParameter(6, java.sql.Types.VARCHAR);

                proc.executeUpdate();
              //  message = proc.getString(6);

               // rs = (ResultSet) proc.getObject(5);

                while (rs.next()) {
                    searchFound = 1;
                    oTrandinStockRegisterBean = new TrandinStockRegisterBean();
                    oTrandinStockRegisterBean.setStock_id(rs.getString(1));
                    oTrandinStockRegisterBean.setName(rs.getString(2));
                    oTrandinStockRegisterBean.setCommoditytype(rs.getString(17));
                    oTrandinStockRegisterBean.setCommoditysubtype(rs.getString(18));
                    oTrandinStockRegisterBean.setEntDate(rs.getString(5));
                    oTrandinStockRegisterBean.setSelectperish(rs.getString(6));
                    oTrandinStockRegisterBean.setStkexpiryDate(rs.getString(7));
                    oTrandinStockRegisterBean.setPrice_unit(rs.getString(8));
                    oTrandinStockRegisterBean.setQuantity(rs.getString(9));
                    oTrandinStockRegisterBean.setQuantity_availed(rs.getString(10));
                    oTrandinStockRegisterBean.setQuantity_available(rs.getString(11));
                    oTrandinStockRegisterBean.setPfnm(rs.getString(12));
                    oTrandinStockRegisterBean.setPfm(rs.getString(13));
                    oTrandinStockRegisterBean.setPurchase_id(rs.getString(14));
                    oTrandinStockRegisterBean.setGodown_id(rs.getString(15));
                    oTrandinStockRegisterBean.setStockdesc(rs.getString(16));

                    alTrandinStockRegisterBean.add(oTrandinStockRegisterBean);
                    request.setAttribute("displayFlag", "Y");

                }
            } catch (SQLException 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) {
                   System.out.println("Error occurred during processing.");
                }
            }
            if (searchFound == 0) {
                message = "No data exists for selected item";
                request.setAttribute("message", message);
            }
           // oTrandinStockRegisterBean.setCheckOption(request.getParameter("checkOption"));
            request.setAttribute("oTrandinStockRegisterBean", oTrandinStockRegisterBean);
            request.setAttribute("arrTrandinStockRegisterBean", alTrandinStockRegisterBean);
            request.setAttribute("message", message);

            request.getRequestDispatcher("/Trading_JSP/TradingStockRegisterEdit.jsp").forward(request, response);

        } if ("EditSubmit".equalsIgnoreCase(ServletName)) 
        {
            try {
               // BeanUtils.populate(oTrandinStockRegisterBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               System.out.println("Error occurred during processing.");
            }

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

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

                  //  String purchaseId = request.getParameter("purchase_id" + i);
                  //  String productId = request.getParameter("stock_id" + i);

                    if (purchaseId != null) {
                        oTrandinStockRegisterBean = new TrandinStockRegisterBean();
                        oTrandinStockRegisterBean.setPurchase_id(purchaseId);
                        oTrandinStockRegisterBean.setProduct_id(productId);
                       // oTrandinStockRegisterBean.setStkexpiryDate(request.getParameter("stkexpiryDate" + i));
                       // oTrandinStockRegisterBean.setSelectperish(request.getParameter("selectperish" + i));
                       // oTrandinStockRegisterBean.setPrice_unit(request.getParameter("price_unit" + i));
                       // oTrandinStockRegisterBean.setQuantity(request.getParameter("quantity" + i));
                       // oTrandinStockRegisterBean.setPfnm(request.getParameter("pfnm" + i));
                       // oTrandinStockRegisterBean.setGodown_id(request.getParameter("godown_id" + i));
                       // oTrandinStockRegisterBean.setStockdesc(request.getParameter("stockdesc" + i));
                       // oTrandinStockRegisterBean.setPfm(request.getParameter("pfm" + i));
                       // oTrandinStockRegisterBean.setCommoditytype(request.getParameter("commoditytype" + i));
                       // oTrandinStockRegisterBean.setCommoditysubtype(request.getParameter("commoditysubtype" + i));
                       // oTrandinStockRegisterBean.setQuantity_availed(request.getParameter("quantity_availed" + i));
                        oTrandinStockRegisterBean.setQuantity_available(request.getParameter("quantity_available" + i));
                        alTrandinStockRegisterBean.add(oTrandinStockRegisterBean);
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }
            if ((alTrandinStockRegisterBean.size() > 0)) {

                try {
                    con = DbHandler.getDBConnection();
                    con.setAutoCommit(false);
                    try {
                        proc = con.prepareCall("{ call trading_operation.upsert_edit_stock_register(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       System.out.println("Error occurred during processing.");
                    }

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

                        oTrandinStockRegisterBean = alTrandinStockRegisterBean.get(j);
                        proc.setString(1, oTrandinStockRegisterBean.getCommoditytype());
                        proc.setString(2, oTrandinStockRegisterBean.getCommoditysubtype());
                        proc.setString(3, oTrandinStockRegisterBean.getProduct_id());
                        proc.setString(4, oTrandinStockRegisterBean.getSelectperish());
                        proc.setString(5, oTrandinStockRegisterBean.getStkexpiryDate());
                        proc.setString(6, oTrandinStockRegisterBean.getPrice_unit());
                        proc.setString(7, oTrandinStockRegisterBean.getQuantity());
                        proc.setString(8, oTrandinStockRegisterBean.getQuantity_availed());
                        proc.setString(9, oTrandinStockRegisterBean.getQuantity_available());
                        proc.setString(10, oTrandinStockRegisterBean.getPfnm());
                        proc.setString(11, oTrandinStockRegisterBean.getPfm());
                        proc.setString(12, oTrandinStockRegisterBean.getPurchase_id());
                        proc.setString(13, oTrandinStockRegisterBean.getGodown_id());
                        proc.setString(14, oTrandinStockRegisterBean.getStockdesc());
                        proc.setString(15, "Update");   
                        proc.setString(16, pacsId);
                        proc.setString(17, user);
                        proc.registerOutParameter(18, java.sql.Types.VARCHAR);
                                                                                                                                                                      
                        proc.execute();
                       // message = proc.getString(18);
                        if (!message.equalsIgnoreCase("Stock Register successfully updated")) {
                            con.rollback();
                            break;
                        }
                    }
                    con.commit();
                } catch (SQLException 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) {
                       System.out.println("Error occurred during connection close.");
                    }
                }
            }
            request.setAttribute("message", message);
            request.getRequestDispatcher("/Trading_JSP/TradingStockRegisterEdit.jsp").forward(request, response);
        
        } else if ("PrintBarCode".equalsIgnoreCase(ServletName)) {


            String indicator = request.getParameter("indicator");
            String inventoryId = request.getParameter("stock_id" + indicator);
            float noOfPrints = Float.valueOf(request.getParameter("qty" + indicator));
            File barcodeFile = new File(FILE_NAME);
//            try {
//                Rectangle pagesize = new Rectangle(215,71);
//		Document document = new Document(pagesize);
//		PdfPTable table = new PdfPTable(2);
//                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(barcodeFile));
//		document.open();
//		document.setMargins(0, 0, 5, 0);
//		table.setWidthPercentage(100);
//               for (int i = 1; i <= noOfPrints; i++) {
//				table.addCell(createBarcode(writer,inventoryId));
//				if(i%2==0)
//				{
//					document.add(table);
//					table = null;
//					table = new PdfPTable(2);
//					table.setWidthPercentage(100);
//				}
//			}
//
//		document.close();
//                if (barcodeFile != null) {
//                    stream = response.getOutputStream();
//                    // request.getSession().setAttribute("errorMessage", result);
//                    //request.setAttribute("message", result);
//                    response.setContentType("application/pdf");
//                    response.addHeader("Content-Disposition", "attachment; filename="
//                            + "Barcode_" + inventoryId + ".pdf");
//                    response.setContentLength((int) barcodeFile.length());
//                    FileInputStream input = new FileInputStream(barcodeFile);
//                    buf = new BufferedInputStream(input);
//                    int readBytes = 0;
//
//                    while ((readBytes = buf.read()) != -1) {
//                        stream.write(readBytes);
//                    }
//
//                    barcodeFile.delete();
//                }
//            } catch (Exception e) {
//               // e.printStackTrace();
//               System.out.println("Error occurred during processing.");
//                request.setAttribute("message", "Error in generating barcode ");
//                request.getRequestDispatcher("/Trading_JSP/TradingStockRegister.jsp").forward(request, response);
//                return;
//            
//            } finally {
//                System.out.println("Processing done.");
//            }
        }
    }
//  public static PdfPCell createBarcode(PdfWriter writer, String code) throws DocumentException, IOException {
//		Barcode128 barcode128 = new Barcode128();
//	        barcode128.setCode(code);
//	        barcode128.setCodeType(Barcode.CODE128);
//	        PdfPCell cell = new PdfPCell(barcode128.createImageWithBarcode(writer.getDirectContent(), null,null), true);
//	        cell.setPadding(11);
//	        cell.setBorderColor(BaseColor.WHITE);
//	        return cell;
//	    }

    @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 {
        processRequest(request, response);
    }

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




