/*
 * 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 981898
 */
public class DirectBenifitTransferServlet 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 DirectBenifitTransferServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet DirectBenifitTransferServlet 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 pacsId = (String) session.getAttribute("pacsId");
        Connection con = null;
        Statement proc = null;
        //String from_date = request.getParameter("from_date");
       // String to_date = request.getParameter("to_date");
        String result = "";
        String qry="";
        System.out.println("Inside DirectBenifitTransferServlet");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=DirectBenifitTransferReport.csv");

        try {

            System.out.println("Inside try block");
            con = DbHandler.getDBConnection();
            proc = con.createStatement();
            qry="select rownum||','||a.txn_date||','||a.cbs_ref_no||','||a.ipks_account_no||','||a.cbs_acct||','||a.narration||','||a.txn_amt||','||A.SYSTEM_DT||','||A.PACS_NAME ";
            qry = qry + "from (select to_char(n.tran_date, 'dd-Mon-yyyy') txn_date,n.cbs_ref_no cbs_ref_no,n.acct_no ipks_account_no,d.link_accno cbs_acct,substr(n.narration, 0, 11) narration,n.txn_amt,(SELECT SYSTEM_DATE FROM SYSTEM_DATE) SYSTEM_DT,PM.PACS_NAME PACS_NAME from dep_txn n, dep_account d, PACS_MASTER PM "
                    + " where n.acct_no = d.key_1 AND PM.PACS_ID = D.PACS_ID and d.dep_prod_id in (select P.ID from dep_product p where p.prod_code = '1101') and d.pacs_id = '" + pacsId + "' and (upper(n.narration) like '%ACH PAYMENT%' or upper(n.narration) like '%UIH PAYMENT%') and n.tran_date between to_date('" + from_date +
                    "', 'dd/mm/yyyy') and to_date('" + to_date + "', 'dd/mm/yyyy') order by to_date(n.tran_date, 'dd-mon-yyyy'), n.acct_no) a";
            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,NARRATION,AMOUNT"+"\r\n";
            if(!rs.isBeforeFirst()){
                result="NO DATA FOUND  ";
            }
            while (rs.next()) {
                String str = rs.getString(1);
                if(str ==null)
                    break;
                else
                result = result + str + "\r\n";
                
            }

            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();
                proc.close();
            } catch (SQLException ex) {
               // Logger.getLogger(DirectBenifitTransferServlet.class.getName()).log(Level.SEVERE, null, ex);
               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>

}
