package performa.form;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import oneit.objstore.StorageException;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.portability.FileDownloader;
import oneit.servlets.process.ORMProcessFormProcessor;
import oneit.servlets.process.ORMProcessState;
import oneit.utils.BusinessException;
import oneit.utils.CollectionUtils;
import oneit.utils.RandomStringGen;
import performa.orm.JobApplication;
import performa.utils.PDFUtils;


public class ApplicantReportFP extends ORMProcessFormProcessor 
{

    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map map)
                                                                                               throws BusinessException,
                                                                                               StorageException
    {
        HttpServletRequest      request         =   submission.getRequest();
        RandomStringGen         rand            =   new RandomStringGen();
        final String            randFileName    =   rand.generateAlphaNum(16) + ".pdf";
        boolean                 showList        =   (boolean) request.getAttribute("ShowList");
        boolean                 applicantPage   =   (boolean) request.getAttribute("ApplicantPage");
        List<JobApplication>    applications    =   (List<JobApplication>) request.getAttribute("Applications");

        final   byte[]      pdfBytes;
                
        if(CollectionUtils.equals(applicantPage, true))
        {
            pdfBytes    =   PDFUtils.generateApplicantReportSummaryPDF(submission);
        }
        else
        {
            Map data    =   CollectionUtils.mapEntry("Applications", applications).toMap();
            
            if(CollectionUtils.equals(showList, true))
            {
                pdfBytes    =   PDFUtils.generateApplicantsListPDF(submission, data);
            }
            else
            {
                pdfBytes    =   PDFUtils.generateApplicantsGridPDF(submission, data);
            }
        }
        
        return new SuccessfulResult()
        {
            @Override
            public void applyResult(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException 
            {
                FileDownloader.writeData(request, response, pdfBytes, "application/pdf", randFileName, false);
            }
        };
    }
    
}