/*
 * 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 CRARRiskMasterServlet 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 glcode = request.getParameter("glcode" + i);
                    
                    if (glcode != null) {
                        oAssetEntryBean = new AssetEntryBean();
                        oAssetEntryBean.setGlcode(glcode);                        
                        //oAssetEntryBean.setDepRate(request.getParameter("depRate" + i));
                       // oAssetEntryBean.setGlid(request.getParameter("glid" + i));
                       // oAssetEntryBean.setRemarks(request.getParameter("remarks" + i));
                       // oAssetEntryBean.setStatus(request.getParameter("status" + i));
                        oAssetEntryBean.setId(request.getParameter("id" + i));
                       // oAssetEntryBean.setComp1(request.getParameter("comp1" + i));
                        //oAssetEntryBean.setComp2(request.getParameter("comp2" + 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 PARAMETER.upsert_crar_risk_master(?,?,?,?,?,?,?,?,?,?) }");
                    } 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, pacsId);
                        proc.setString(2, oAssetEntryBean.getGlid());
                        proc.setString(3, oAssetEntryBean.getComp1());
                        proc.setString(4, oAssetEntryBean.getComp2());
                        proc.setString(5, oAssetEntryBean.getDepRate());
                        proc.setString(6, oAssetEntryBean.getRemarks());
                        proc.setString(7, user);
                        proc.setString(8, Action);
                        proc.setString(9, oAssetEntryBean.getStatus());
                        proc.registerOutParameter(10, java.sql.Types.VARCHAR);                        
                        
                        proc.execute();

                       // message = proc.getString(10);
                        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/crarRiskMaster.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 glcode = request.getParameter("glcode" + i);
                    
                    if (glcode != null) {
                        oAssetEntryBean = new AssetEntryBean();
                        oAssetEntryBean.setAsset_type(glcode);                        
                        //oAssetEntryBean.setDepRate(request.getParameter("depRate" + i));
                        //oAssetEntryBean.setGlid(request.getParameter("glid" + i));
                       // oAssetEntryBean.setRemarks(request.getParameter("remarks" + i));
                       // oAssetEntryBean.setStatus(request.getParameter("status" + i));
                        oAssetEntryBean.setId(request.getParameter("id" + i));
                       // oAssetEntryBean.setComp1(request.getParameter("comp1" + i));
                       // oAssetEntryBean.setComp2(request.getParameter("comp2" + 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 PARAMETER.upsert_crar_risk_master(?,?,?,?,?,?,?,?,?,?) }");
                    } 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, pacsId);
                        proc.setString(2, oAssetEntryBean.getGlid());
                        proc.setString(3, oAssetEntryBean.getComp1());
                        proc.setString(4, oAssetEntryBean.getComp2());
                        proc.setString(5, oAssetEntryBean.getDepRate());
                        proc.setString(6, oAssetEntryBean.getRemarks());
                        proc.setString(7, user);
                        proc.setString(8, Action);
                        proc.setString(9, oAssetEntryBean.getStatus());
                        proc.registerOutParameter(10, java.sql.Types.VARCHAR);                        
                        
                        proc.execute();

                       // message = proc.getString(10);
                        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/crarRiskMaster.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 pacs_id, gl_class_code id, comp1, comp2, (select max(t.prod_name) from trial_balance_shadow t where t.pacs_id = r.pacs_id and t.ledger_dt = (select system_date - 1 from system_date) and substr(t.glcc, 9, 10) = r.gl_class_code) gl_name, rist_percentage, status from crar_risk_master r where r.pacs_id = '" + pacsId + "' ");

                while (resultset.next()) {
                    
                        oAssetEntryBean = new AssetEntryBean();
                        oAssetEntryBean.setGlid(resultset.getString("id"));
                        oAssetEntryBean.setGlcode(resultset.getString("gl_name"));
                        oAssetEntryBean.setDepRate(resultset.getString("rist_percentage"));
                        oAssetEntryBean.setStatus(resultset.getString("status"));
                        oAssetEntryBean.setComp1(resultset.getString("comp1"));
                        oAssetEntryBean.setComp2(resultset.getString("comp2"));
                        
                    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/crarRiskMaster.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";
    }
}
