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

import LoginDb.DbHandler;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
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 java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.ServletOutputStream;

/**
 *
 * @author 1004242
 */
public class InwardCsvServlet 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 {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet InwardCsvServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet InwardCsvServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <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 {
        HttpSession session = request.getSession(false);

        String message = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
        String handle_id = request.getParameter("handle_id");
        String userRole = (String) session.getAttribute("userRole");
        Connection con = null;
        Statement proc = null;       
        CallableStatement stmt = null;
       // String from_date = request.getParameter("from_date");
       // String to_date = request.getParameter("to_date");
        String result = "";
        String qry="";
        System.out.println("Inside InwardCsvServlet");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=inward_report.csv");

        try {

            System.out.println("Inside try block");
            con = DbHandler.getDBConnection();
            proc = con.createStatement();
            qry="select i.txn_date||','||i.ref_no||','||i.key_1||','||i.ipks_acc_no||','||'NEFT'||','||txn_amt||','||i.remitter_details from inward_neft_new_bkp i where i.proc_flag = 'Y' and i.status = 'POSTED' and i.pacs_id = " + pacsId + " and to_date(i.txn_date, 'dd-mon-yyyy') between to_date('" + from_date + "', 'dd/mm/yyyy') and to_date('" + to_date + "', 'dd/mm/yyyy') order by i.txn_date";
            System.out.println(qry);
            //ResultSet rs = proc.executeQuery(qry);

            System.out.println("Query executed");
            result = "SL NO,DATE,REFERENCE NO,IPKS A/C NO,LINK A/C NO,TRANSACTIO,AMOUNT,REMITTER DETAILS"+"\r\n";
            int counter =1;
            while (rs.next()) {
                String str = rs.getString(1);
                if(str ==null)
                    break;
                else
                result = result + counter+","+str + "\r\n";
                counter++;
            }

            if(result!=null){
                result=result.substring(0,result.length()-2);
            }

            System.out.println(result);
            InputStream in = new ByteArrayInputStream(result.getBytes("UTF-8"));
            ServletOutputStream out = response.getOutputStream();

            byte[] outputByte = new byte[1024];
            //copy binary contect to output stream
            int n =0;
           // while ((n=in.read(outputByte, 0, 1024)) != -1) {
                out.write(outputByte, 0, n);
            }
            in.close();
            out.flush();
            out.close();
        } catch (Exception e) {
          // e.printStackTrace();
          System.out.println("Error Occurred during processing.");
        } finally {
            try {
                con.close();
            } catch (SQLException e) {
               // System.out.println(e.toString());
               System.out.println("Error Occurred during connection close.");
            }
        }
    }

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