/*
 * 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 AccountRewnewBulkServlet 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");
        String filePath = null;

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

        try {
            if (ServletFileUpload.isMultipartContent(request)) {
                filePath = service.uploadCSVToServer(request,pacsId);
                if (filePath != null) {
                    String result = service.readAndInsertFromCSVForAccountRenewBulk(pacsId, filePath,tellerId);
                    if(result !=null)
                    {
                        request.getSession().setAttribute("errorMessageAccBulk", result);
                    }else
                    {
                        request.getSession().setAttribute("errorMessageAccBulk", "Error occured during process. Please try again.");
                    }
                    System.out.println(request.getHeaderNames());
                   // 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/KCC_ACCT_RENEWAL.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("Accnt renew Bulk format file downloaded for pacs id :" + pacsId);
        }

        } catch (Exception e) {
           // e.printStackTrace();
            System.out.println("Error occurred during processing.");
            request.getSession().setAttribute("errorMessageAccBulk", "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>
}
