package Controller;

import DataEntryBean.DistScaleOfFinanceBean;
import LoginDb.DbHandler;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
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;

























public class DistScaleOfFinanceServlet
  extends HttpServlet
{
  public DistScaleOfFinanceServlet() {}

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    HttpSession session = request.getSession(false);
    Statement statement = null;
    Connection con = null;
    CallableStatement proc = null;
    String message = "";
    int flag = 1;
    String counter = request.getParameter("all_rowsAdded");
    String counter2 = request.getParameter("all_rowsAdded2");
    String user = (String)session.getAttribute("user");
    String handle = request.getParameter("handle_id");
    //String year = request.getParameter("checkYear2");
    //String code = request.getParameter("distCode2");
    //String name = request.getParameter("distName2");
    if (handle.equalsIgnoreCase("Create"))
    {
      DistScaleOfFinanceBean oDistScaleOfFinanceBean = new DistScaleOfFinanceBean();
      try {
       // BeanUtils.populate(oDistScaleOfFinanceBean, request.getParameterMap());
      } catch (IllegalAccessException ex) {
        flag = 0;
       // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
       System.out.println("Error occurred during processing.");
      } catch (InvocationTargetException ex) {
        flag = 0;
       // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
       System.out.println("Error occurred during processing.");
      }
      try
      {
        con = DbHandler.getDBConnection();
        try {
          proc = con.prepareCall("{ call dist_scale_finance(?,?,?,?,?,?,?,?,?,?,?,?) }");
        } catch (SQLException ex) {
         // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println("Error occurred during processing.");
        }

        int i = 1;

        while (i <= Integer.parseInt(counter) + 1)
        {
          if (request.getParameterMap().containsKey("chckbox" + i)) {
            String val = request.getParameter("chckbox" + i);

            if (val.equalsIgnoreCase("1"))
            {
             // String totcost = request.getParameter("totalCost" + i);
              proc.setString(1, oDistScaleOfFinanceBean.getDistCode());
             // proc.setString(2, request.getParameter("cropCode" + i));
             // proc.setString(3, request.getParameter("seedCost" + i));
             // proc.setString(4, request.getParameter("manureCost" + i));
             // proc.setString(5, request.getParameter("fertilizerCost" + i));
             // proc.setString(6, request.getParameter("pesticidesCost" + i));
             // proc.setString(7, request.getParameter("irrigationCost" + i));
             // proc.setString(8, request.getParameter("labourCost" + i));
              proc.setString(9, totcost);
             // proc.setString(10, request.getParameter("checkYear"));
              proc.registerOutParameter(11, java.sql.Types.VARCHAR);
              proc.registerOutParameter(12, java.sql.Types.INTEGER);

              proc.execute();

             // message = proc.getString(11);
            }
          }
          i++;
        }
      }
      catch (SQLException ex) {
        flag = 0;
       // Logger.getLogger(DistScaleOfFinanceServlet.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) {
          flag = 0;
         // System.out.println(e.toString());
         System.out.println("Error occurred during proc close.");
        }
        try {
          con.close();
        } catch (SQLException ex) {
          flag = 0;
         // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
         // System.out.println(ex.toString());
         System.out.println("Error occurred during processing.");
        }

        if ((flag == 1) && ((message == null) || (message == "")))
        {
          message = "Record successfully inserted";
        }
        request.setAttribute("message", message);
        request.getRequestDispatcher("/distScaleOfFinance.jsp").forward(request, response);
      }
    }


    if (handle.equalsIgnoreCase("Fetch")) {
      ArrayList<DistScaleOfFinanceBean> alMyDistScaleOfFinanceBean = new ArrayList();
      DistScaleOfFinanceBean oDistScaleOfFinanceBean = new DistScaleOfFinanceBean();
      try
      {
        //BeanUtils.populate(oDistScaleOfFinanceBean, request.getParameterMap());
      } catch (IllegalAccessException ex) {
       // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
       System.out.println("Error occurred during processing.");
      } catch (InvocationTargetException ex) {
       // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
       System.out.println("Error occurred during processing.");
      }
      try
      {
        con = DbHandler.getDBConnection();
        try {
          proc = con.prepareCall("{ call dist_scale_finance_amend(?,?,?,?,?) }");
        }
        catch (SQLException ex) {
         // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println("Error occurred during processing.");
        }

        int i = 1;
        ResultSet rs = null;

        //proc.setString(1, request.getParameter("checkYear2"));
       // proc.setString(2, request.getParameter("distCode2"));
        proc.registerOutParameter(3, -10);
        proc.registerOutParameter(4, 12);
        proc.registerOutParameter(5, 4);

        proc.execute();

       // message = proc.getString(4);
       // rs = (ResultSet)proc.getObject(3);
        flag = 0;
        while (rs.next())
        {
          DistScaleOfFinanceBean DistScaleOfFinanceBeanObj = new DistScaleOfFinanceBean();

          DistScaleOfFinanceBeanObj.setCropName(rs.getString("crop_name"));
          DistScaleOfFinanceBeanObj.setCropCode(rs.getString("crop_code"));
          DistScaleOfFinanceBeanObj.setSeedCost(rs.getString("seed_cost"));
          DistScaleOfFinanceBeanObj.setManureCost(rs.getString("manure_cost"));
          DistScaleOfFinanceBeanObj.setFertilizerCost(rs.getString("fertilizer_cost"));
          DistScaleOfFinanceBeanObj.setPesticidesCost(rs.getString("pesticides_cost"));
          DistScaleOfFinanceBeanObj.setIrrigationCost(rs.getString("irrigation_cost"));
          DistScaleOfFinanceBeanObj.setLabourCost(rs.getString("labour_cost"));
          DistScaleOfFinanceBeanObj.setTotalCost(rs.getString("total_cost"));
          alMyDistScaleOfFinanceBean.add(DistScaleOfFinanceBeanObj);
          request.setAttribute("displayFlag", "Y");
          flag = 1;
        }
      }
      catch (SQLException ex)
      {
        flag = 0;
       // Logger.getLogger(DistScaleOfFinanceServlet.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) {
          flag = 0;
         // System.out.println(e.toString());
         System.out.println("Error occurred during proc close.");
        }
        try {
          con.close();
        } catch (SQLException ex) {
          flag = 0;
         // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
         // System.out.println(ex.toString());
         System.out.println("Error occurred during processing.");
        }

        request.setAttribute("year", year);
        request.setAttribute("code", code);
        request.setAttribute("name", name);
        request.setAttribute("oDistScaleOfFinanceBean", oDistScaleOfFinanceBean);
        request.setAttribute("alMyDistScaleOfFinanceBean", alMyDistScaleOfFinanceBean);

        if ((flag == 0) && ((message == null) || (message == "")))
        {
          message = "No records to display";
        }
        request.setAttribute("message", message);

        request.getRequestDispatcher("/distScaleOfFinance.jsp").forward(request, response);
      }
    }


    if (handle.equalsIgnoreCase("Update"))
    {
      DistScaleOfFinanceBean oDistScaleOfFinanceBean = new DistScaleOfFinanceBean();
      PreparedStatement ps = null;
      try {
       // BeanUtils.populate(oDistScaleOfFinanceBean, request.getParameterMap());
      } catch (IllegalAccessException ex) {
        flag = 0;
       // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
       System.out.println("Error occurred during processing.");
      } catch (InvocationTargetException ex) {
        flag = 0;
       // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
       System.out.println("Error occurred during processing.");
      }
      try
      {
        con = DbHandler.getDBConnection();
        try
        {
          String q = "update dist_scale_of_finance set seed_cost=?,manure_cost=?,fertilizer_cost=?,pesticides_cost=?,irrigation_cost=?,labour_cost=?,total_cost=? where financial_year=? and dist_code=? and crop_name=?";
          ps = con.prepareStatement(q);
        } catch (SQLException ex) {
          flag = 0;
         // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
         System.out.println("Error occurred during processing.");
        }

        int i = 1;
        flag = 0;
        while (i <= Integer.parseInt(counter2))
        {


         // String totcost = request.getParameter("totalCostTwo" + i);
          //ps.setString(1, request.getParameter("seedCostTwo" + i));
         // ps.setString(2, request.getParameter("manureCostTwo" + i));
          //ps.setString(3, request.getParameter("fertilizerCostTwo" + i));
         // ps.setString(4, request.getParameter("pesticidesCostTwo" + i));
         // ps.setString(5, request.getParameter("irrigationCostTwo" + i));
         // ps.setString(6, request.getParameter("labourCostTwo" + i));
         // ps.setString(7, totcost);
         // ps.setString(8, request.getParameter("checkYear2"));
         // ps.setString(9, request.getParameter("distCode2"));
         // ps.setString(10, request.getParameter("cropCodeTwo" + i));


          ps.executeUpdate();
          flag = 1;


          i++;
        }
      }
      catch (SQLException ex) {
        flag = 0;
       // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
       // System.out.println(ex.toString());
       System.out.println("Error occurred during processing.");
      } finally {
        try {
          ps.close();
        } catch (SQLException e) {
          flag = 0;
         // System.out.println(e.toString());
         System.out.println("Error occurred during statement close.");
        }
        try {
          con.close();
        } catch (SQLException ex) {
          flag = 0;
         // Logger.getLogger(DistScaleOfFinanceServlet.class.getName()).log(Level.SEVERE, null, ex);
         // System.out.println(ex.toString());
         System.out.println("Error occurred during connection close.");
        }

        if ((flag == 1) && ((message == null) || (message == "")))
        {
          message = "Records successfully updated";
        }
        request.setAttribute("message", message);
        request.getRequestDispatcher("/distScaleOfFinance.jsp").forward(request, response);
      }
    }
  }
}
