/*
 * 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.AssetEntryBean;
import LoginDb.DbHandler;
import java.io.IOException;
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 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;
import java.lang.reflect.InvocationTargetException;

/**
 *
 * @author Tcs Help desk122
 */
public class AssetEntryServlet extends HttpServlet {

    protected void processRequest(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 Action = request.getParameter("handle_id");
        //String checkOpt = request.getParameter("checkOption");

        AssetEntryBean oAssetEntryBean = new AssetEntryBean();
        ArrayList<AssetEntryBean> alAssetEntryBean = new ArrayList<AssetEntryBean>();
        
        try {
               // BeanUtils.populate(oAssetEntryBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               System.out.println("Error occurred during processing.");
            } catch (InvocationTargetException ex) {
               System.out.println("Error occurred during processing.");
            }

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

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

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

                    String asset_type = request.getParameter("asset_type" + i);
                    
                    if (asset_type != null) {
                        oAssetEntryBean = new AssetEntryBean();
                        oAssetEntryBean.setAsset_type(asset_type);
                        oAssetEntryBean.setAsset_subtype(request.getParameter("asset_subtype" + i));
                        
                        oAssetEntryBean.setGlcode(request.getParameter("glcode" + i));
                        oAssetEntryBean.setDepRate(request.getParameter("depRate" + i));
                        oAssetEntryBean.setGlcode(request.getParameter("glcode" + i));
                        oAssetEntryBean.setGlid(request.getParameter("glid" + i));
                        oAssetEntryBean.setStatus(request.getParameter("status" + i));
                        oAssetEntryBean.setId(request.getParameter("id" + i));
                        //alAssetEntryBean.add(oAssetEntryBean);
                    }
               // } catch (Exception e) {
                   // System.out.println("Error occurred during processing.");
                }
            }
            if ((alAssetEntryBean.size() > 0)) {

                try {                    
                    con = DbHandler.getDBConnection();
                    con.setAutoCommit(false);
                    try {
                        proc = con.prepareCall("{ call ASSET_OPERATION.asset_entry(?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       System.out.println("Error occurred during processing.");
                    }
                    
                    for (int j = 0; j < alAssetEntryBean.size(); j++) {

                        oAssetEntryBean = alAssetEntryBean.get(j);
                        proc.setString(1, oAssetEntryBean.getAsset_id());
                        proc.setString(2, oAssetEntryBean.getAsset_mst_id());
                        proc.setString(3, oAssetEntryBean.getDescription());
                        proc.setString(4, oAssetEntryBean.getCurr_val());
                        proc.setString(5, oAssetEntryBean.getMode_of_aqr());
                        proc.setString(6, pacsId);
                        proc.registerOutParameter(7, java.sql.Types.VARCHAR);
                        proc.setString(8, oAssetEntryBean.getPurchaseDate());
                        proc.setString(9, oAssetEntryBean.getGlid());
                        proc.setString(10, oAssetEntryBean.getDepRate());
                        proc.setString(11, Action);
                        proc.setString(12, oAssetEntryBean.getStatus());
                        proc.setString(13, user);
                        
                        proc.execute();

                        //message = proc.getString(7);
                        if (!message.contains("Successfully")) {
                            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("/Asset_JSP/assetEntry.jsp").forward(request, response);
        
        } else if ("Amend".equalsIgnoreCase(Action)) {            

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

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

                    String asset_type = request.getParameter("asset_type" + i);
                    
                    if (asset_type != null) {
                        oAssetEntryBean = new AssetEntryBean();
                        oAssetEntryBean.setAsset_type(asset_type);
                        oAssetEntryBean.setAsset_subtype(request.getParameter("asset_subtype" + i));
                       // oAssetEntryBean.setAsset_id(request.getParameter("asset_id" + i));
                       // oAssetEntryBean.setDescription(request.getParameter("description" + i));
                       // oAssetEntryBean.setCurr_val(request.getParameter("curr_val" + i));
                      //  oAssetEntryBean.setMode_of_aqr(request.getParameter("mode_of_aqr" + i));
                       // oAssetEntryBean.setAsset_mst_id(request.getParameter("asset_mst_id" + i));
                       // oAssetEntryBean.setPurchaseDate(request.getParameter("purchaseDate" + i));
                        oAssetEntryBean.setGlcode(request.getParameter("glcode" + i));
                        //oAssetEntryBean.setDepRate(request.getParameter("depRate" + i));
                        oAssetEntryBean.setGlcode(request.getParameter("glcode" + i));
                        //oAssetEntryBean.setGlid(request.getParameter("glid" + i));
                        //oAssetEntryBean.setStatus(request.getParameter("status" + i));
                        oAssetEntryBean.setId(request.getParameter("id" + i));
                        alAssetEntryBean.add(oAssetEntryBean);
                    }
                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }
            if ((alAssetEntryBean.size() > 0)) {

                try {                    
                    con = DbHandler.getDBConnection();
                    con.setAutoCommit(false);
                    try {
                        proc = con.prepareCall("{ call ASSET_OPERATION.asset_entry(?,?,?,?,?,?,?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       System.out.println("Error occurred during processing.");
                    }
                    
                    for (int j = 0; j < alAssetEntryBean.size(); j++) {

                        oAssetEntryBean = alAssetEntryBean.get(j);
                        proc.setString(1, oAssetEntryBean.getAsset_id());
                        proc.setString(2, oAssetEntryBean.getAsset_mst_id());
                        proc.setString(3, oAssetEntryBean.getDescription());
                        proc.setString(4, oAssetEntryBean.getCurr_val());
                        proc.setString(5, oAssetEntryBean.getMode_of_aqr());
                        proc.setString(6, pacsId);
                        proc.registerOutParameter(7, java.sql.Types.VARCHAR);
                        proc.setString(8, oAssetEntryBean.getPurchaseDate());
                        proc.setString(9, oAssetEntryBean.getGlid());
                        proc.setString(10, oAssetEntryBean.getDepRate());
                        proc.setString(11, Action);
                        proc.setString(12, oAssetEntryBean.getStatus());
                        proc.setString(13, user);
                        
                        proc.execute();
                       // message = proc.getString(7);
                        if (!message.contains("Successfully")) {
                            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("/Asset_JSP/assetEntry.jsp").forward(request, response);
        
        } else if ("getDetails".equalsIgnoreCase(Action)) {
            
            ResultSet resultset = null;
            Statement statement = null;            
            
            Connection connection = DbHandler.getDBConnection();
            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               System.out.println("Error occurred during processing.");
            }
            try {
                //resultset = statement.executeQuery("select id, asset_mst_id, asset_id, (select asset_type || ':' || TYPE_DESC from asset_master li where li.id = reg.asset_mst_id) asset_type, (select asset_subtype || ':' || SUBTYPE_DESC from asset_master li where li.id = reg.asset_mst_id) asset_subtype, description, initial_value purchase_value, decode(reg.acquirement, 'p', 'Purchase', 'o', 'Others', 'Donation') as acquirement, to_char(reg.entry_date, 'DD/MM/YYYY') as purchase_dt, to_char(reg.last_eval_date, 'DD/MM/YYYY') as entry_date, asset_gl_class gl_code, (select max(gp.gl_name) from gl_product gp where gp.comp1 || gp.comp2 = reg.asset_gl_class) gl_name, depre_rate, active_flag   from asset_register reg  where pacs_id = '" +pacsId+ "' order by 2, last_eval_date ");               

                while (resultset.next()) {
                    
                        oAssetEntryBean = new AssetEntryBean();
                        oAssetEntryBean.setId(resultset.getString("id"));
                        oAssetEntryBean.setAsset_type(resultset.getString("asset_type"));
                        oAssetEntryBean.setAsset_subtype(resultset.getString("asset_subtype"));
                        oAssetEntryBean.setAsset_mst_id(resultset.getString("asset_mst_id"));
                        oAssetEntryBean.setAsset_id(resultset.getString("asset_id"));
                        oAssetEntryBean.setDescription(resultset.getString("description"));
                        oAssetEntryBean.setCurr_val(resultset.getString("purchase_value"));
                        oAssetEntryBean.setMode_of_aqr(resultset.getString("acquirement"));
                        oAssetEntryBean.setPurchaseDate(resultset.getString("purchase_dt"));
                        oAssetEntryBean.setGlid(resultset.getString("gl_code"));
                        oAssetEntryBean.setGlcode(resultset.getString("gl_name"));
                        oAssetEntryBean.setDepRate(resultset.getString("depre_rate"));
                        oAssetEntryBean.setStatus(resultset.getString("active_flag"));
                        
                    alAssetEntryBean.add(oAssetEntryBean);
                    request.setAttribute("displayFlag", "Y");
                }
            } catch (SQLException ex) {
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    statement.close();
                    resultset.close();
                } catch (SQLException e) {
                    System.out.println("Error occurred during proc close.");
                }
                try {
                    connection.close();
                } catch (SQLException ex) {
                   System.out.println("Error occurred during processing.");
                }
            }            
            request.setAttribute("checkOption", checkOpt);
            request.setAttribute("oAssetEntryBean", oAssetEntryBean);
            request.setAttribute("arrAssetEntryBean", alAssetEntryBean);
            request.getRequestDispatcher("/Asset_JSP/assetEntry.jsp").forward(request, response);
        }
    }

    @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";
    }
}
