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

import DataEntryBean.MicroFileAccountDetBean;
import ServiceLayer.MicrofileProcessingService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author 1004242
 */
public class BulkFileUploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    /**
     * 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);
        MicrofileProcessingService service = new MicrofileProcessingService();
        String pacsId = (String) session.getAttribute("pacsId");
        String tellerId = (String) session.getAttribute("user");
        StringBuilder csvDownloadableBuilder = null;
        String action = (request.getParameter("actionTag") == null) ? request.getParameter("actionMap") : request.getParameter("actionTag");
        String filePath = null;
        String outMsg = null;
        File prtFile = null;

        if (request.getSession().getAttribute("errorMessage") != null) {
            request.getSession().removeAttribute("errorMessage");
        }

        try {
            if (ServletFileUpload.isMultipartContent(request)) {

                filePath = service.uploadCSVToServer(request, pacsId);
                String extentionFile[] = filePath.split("\\.");

                if (extentionFile[1] != null && extentionFile[1].contains("prt")) {

                    if (filePath != null) {
                        outMsg = service.readAndInsertFromPRT(pacsId, filePath, tellerId);
                        if (outMsg != null) {
                            prtFile = new File(filePath);
                            if (prtFile.exists()) {
                                prtFile.delete();
                            }
                            request.setAttribute("message", outMsg);
                        } else {
                            request.setAttribute("message", "Error occured during process. Please try again.");
                        }
                        //response.sendRedirect(request.getHeader("Referer"));
                        request.getRequestDispatcher("/Deposit/BulkFileUpload.jsp").forward(request, response);
                    } else {
                        System.out.println("prt file could not  be read for :" + pacsId);
                        request.setAttribute("message", "Request can not be processed this time");
                        request.getRequestDispatcher("/Deposit/BulkFileUpload.jsp").forward(request, response);
                        //response.sendRedirect(request.getHeader("Referer"));
                        //error case handling
                    }

                } else if (extentionFile[1] != null && extentionFile[1].contains("csv")) {
                    //filePath = service.uploadCSVToServer(request, pacsId);
                    if (filePath != null) {
                        String result = service.readAndInsertFromCSVForBulk(pacsId, filePath, tellerId);
                        if (result != null) {
                            request.getSession().setAttribute("errorMessageBulk", result);
                        } else {
                            request.getSession().setAttribute("errorMessageBulk", "Error occured during process. Please try again.");
                        }
                        //response.sendRedirect(request.getHeader("Referer"));
                    } else {
                        System.out.println("Bulk file could not  be read for :" + pacsId);
                        request.getSession().setAttribute("errorMessage", "Request can not be processed this time");
                       // response.sendRedirect(request.getHeader("Referer"));
                        //error case handling
                    }
                }
            } else if (action != null && action.equalsIgnoreCase("Download")) {

                String filePathSample = this.getServletContext().getRealPath("/WEB-INF/BULK_TXN_FORMAT.xlsx");
                File downloadFile = new File(filePathSample);
                FileInputStream inStream = new FileInputStream(downloadFile);
                // obtains ServletContext
                ServletContext context = getServletContext();
                // gets MIME type of the file
                String mimeType = context.getMimeType(filePathSample);
                if (mimeType == null) {
                    // set to binary type if MIME mapping not found
                    mimeType = "application/octet-stream";
                }
                // modifies response
                response.setContentType(mimeType);
                response.setContentLength((int) downloadFile.length());

                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
                response.setHeader(headerKey, headerValue);
                // obtains response's output stream
                OutputStream outStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                inStream.close();
                outStream.close();
                System.out.println("Bulk format file downloaded for pacs id :" + pacsId);
            }
            else if (action != null && action.equalsIgnoreCase("Manual")) {

                String filePathSample = this.getServletContext().getRealPath("/WEB-INF/BULK TXN POSTING STEPS DETAILS.docx");
                File downloadFile = new File(filePathSample);
                FileInputStream inStream = new FileInputStream(downloadFile);
                // obtains ServletContext
                ServletContext context = getServletContext();
                // gets MIME type of the file
                String mimeType = context.getMimeType(filePathSample);
                if (mimeType == null) {
                    // set to binary type if MIME mapping not found
                    mimeType = "application/octet-stream";
                }
                // modifies response
                response.setContentType(mimeType);
                response.setContentLength((int) downloadFile.length());

                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
                response.setHeader(headerKey, headerValue);
                // obtains response's output stream
                OutputStream outStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                inStream.close();
                outStream.close();
                System.out.println("Manual file downloaded for pacs id :" + pacsId);
            }
            else if (action != null && action.equalsIgnoreCase("CBSBULK")) {

                String filePathSample = this.getServletContext().getRealPath("/WEB-INF/CBS_BULK_ACCT_MANUAL.doc");
                File downloadFile = new File(filePathSample);
                FileInputStream inStream = new FileInputStream(downloadFile);
                // obtains ServletContext
                ServletContext context = getServletContext();
                // gets MIME type of the file
                String mimeType = context.getMimeType(filePathSample);
                if (mimeType == null) {
                    // set to binary type if MIME mapping not found
                    mimeType = "application/octet-stream";
                }
                // modifies response
                response.setContentType(mimeType);
                response.setContentLength((int) downloadFile.length());

                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
                response.setHeader(headerKey, headerValue);
                // obtains response's output stream
                OutputStream outStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                inStream.close();
                outStream.close();
                System.out.println("Manual file downloaded for pacs id :" + pacsId);
            }
            else if (action != null && action.equalsIgnoreCase("MOC")) {

                String filePathSample = this.getServletContext().getRealPath("/WEB-INF/IPKS MOC.pdf");
                File downloadFile = new File(filePathSample);
                FileInputStream inStream = new FileInputStream(downloadFile);
                // obtains ServletContext
                ServletContext context = getServletContext();
                // gets MIME type of the file
                String mimeType = context.getMimeType(filePathSample);
                if (mimeType == null) {
                    // set to binary type if MIME mapping not found
                    mimeType = "application/octet-stream";
                }
                // modifies response
                response.setContentType(mimeType);
                response.setContentLength((int) downloadFile.length());

                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
                response.setHeader(headerKey, headerValue);
                // obtains response's output stream
                OutputStream outStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                inStream.close();
                outStream.close();
                System.out.println("Manual file downloaded for pacs id :" + pacsId);
            }
            else if (action != null && action.equalsIgnoreCase("PSetup")) {

                String filePathSample = this.getServletContext().getRealPath("/WEB-INF/PASSBOOK_SETUP.doc");
                File downloadFile = new File(filePathSample);
                FileInputStream inStream = new FileInputStream(downloadFile);
                // obtains ServletContext
                ServletContext context = getServletContext();
                // gets MIME type of the file
                String mimeType = context.getMimeType(filePathSample);
                if (mimeType == null) {
                    // set to binary type if MIME mapping not found
                    mimeType = "application/octet-stream";
                }
                // modifies response
                response.setContentType(mimeType);
                response.setContentLength((int) downloadFile.length());

                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
                response.setHeader(headerKey, headerValue);
                // obtains response's output stream
                OutputStream outStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                inStream.close();
                outStream.close();
                System.out.println("Manual file downloaded for pacs id :" + pacsId);
            }
            else if (action != null && action.equalsIgnoreCase("SPassbook")) {

                String filePathSample = this.getServletContext().getRealPath("/WEB-INF/Passbook_Sample.jpg");
                File downloadFile = new File(filePathSample);
                FileInputStream inStream = new FileInputStream(downloadFile);
                // obtains ServletContext
                ServletContext context = getServletContext();
                // gets MIME type of the file
                String mimeType = context.getMimeType(filePathSample);
                if (mimeType == null) {
                    // set to binary type if MIME mapping not found
                    mimeType = "application/octet-stream";
                }
                // modifies response
                response.setContentType(mimeType);
                response.setContentLength((int) downloadFile.length());

                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
                response.setHeader(headerKey, headerValue);
                // obtains response's output stream
                OutputStream outStream = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int bytesRead = -1;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                inStream.close();
                outStream.close();
                System.out.println("Manual file downloaded for pacs id :" + pacsId);
            }


        } catch (Exception e) {
           // e.printStackTrace();
           System.out.println("Error occurred during processing.");
            request.getSession().setAttribute("errorMessageBulk", "Request can not be processed.");
           // response.sendRedirect(request.getHeader("Referer"));

        } finally { 
                    System.out.println("Processing done."); 
                }

    }

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