/*
 * 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.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 MicroFileProcesssingServlet 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 agentId = request.getParameter("agentId");
        String tellerId = (String)session.getAttribute("user");
        String action = request.getParameter("actionTag");
        StringBuilder csvDownloadableBuilder = null;
        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) {
                    MicroFileAccountDetBean resultDetails = service.readAndInsertFromCSV(pacsId, filePath,tellerId);
                    System.out.println("No of Handbill entry inserted :" + resultDetails.getSuccessfulRecords() + " for pacs Id :" + pacsId);
                    File fileToBeDwlted = new File(filePath);
                    fileToBeDwlted.delete();//delete the file created locally
                    if(resultDetails.getSuccessfulRecords() == resultDetails.getTotalRecords())
                        request.getSession().setAttribute("errorMessage", resultDetails.getSuccessfulRecords() + " out of "+resultDetails.getTotalRecords() +" details has been submitted succesfully");
                    else if (resultDetails.getSuccessfulRecords() < resultDetails.getTotalRecords())
                        request.getSession().setAttribute("errorMessage", resultDetails.getSuccessfulRecords() + " out of "+resultDetails.getTotalRecords() +" details has been processed. Please check for duplicate entry in your csv.");
                   // response.sendRedirect(request.getHeader("Referer"));
                } else {
                    System.out.println("EOD balance 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")) {
                csvDownloadableBuilder = service.downloadCsvFile(pacsId,agentId);
                if (csvDownloadableBuilder != null) {
                    response.setContentType("text/csv");
                    response.setHeader("Content-Disposition", "attachment; filename=\"GL14-testfile.csv\"");
                    OutputStream outputStream = response.getOutputStream();
                    outputStream.write(csvDownloadableBuilder.toString().getBytes());
                    outputStream.flush();
                    outputStream.close();
                    System.out.println("Balance file downloaded for pacs id :" + pacsId);
                } else {

                    //return message;
                    System.out.println("Balance file could not get downloaded for pacs id :" + pacsId);
                    request.getSession().setAttribute("errorMessage", "No Record found for the given request.");
                  //  response.sendRedirect(request.getHeader("Referer"));
                }
            }
        } catch (Exception e) {
           // e.printStackTrace();
            System.out.println("Error occurred during processing.");
            request.getSession().setAttribute("errorMessage", "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>
}
