package performa.form;

import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import oneit.logging.*;
import oneit.objstore.*;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.servlets.forms.*;
import oneit.servlets.jsp.TableTag;
import oneit.servlets.portability.FileDownloader;
import oneit.servlets.process.*;
import oneit.utils.*;
import oneit.utils.table.*;
import performa.orm.TestInput;

/**
 *
 * @author Pradip J. Sabhadiya
 */
public class TestAnalysisFP extends ORMProcessFormProcessor
{
    private static final    List<String>    SUPPORTED_TYPES =   new ArrayList<>(Arrays.asList("text/csv", "text/plain"));
    
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        TestInput               testInput   = (TestInput) process.getAttribute("TestAnalysis");
        ByteArrayOutputStream   bos         = new ByteArrayOutputStream ();
        byte[]                  bytes;
        //TO-DO -> "filecontent" processing
        
        try
        {
            ExcelExporter.ExportAppender    excelRenderer   = getExportAppender(testInput.getCSV());
            excelRenderer.export(bos);
            bytes = bos.toByteArray();
        }
        catch(IOException ioe)
        {
            LogMgr.log(LoggingArea.ALL, LogLevel.PROCESSING1, ioe, "Exception occurred while Creating Excel File.");
            
            throw new BusinessException(ioe.getMessage());
        }

        return (HttpServletRequest request, HttpServletResponse response) ->
        {
            FileDownloader.writeData(request, response, bytes, TableTag.EXCEL_MIME_TYPE, "Result.xls", false);
        };
    }
    
    private static ExcelExporter.ExportAppender getExportAppender(BinaryContent file) throws IOException
    {
        Properties props = new Properties();
        props.load(TestAnalysisFP.class.getClassLoader().getResourceAsStream("excel-styles.properties"));

        props.put("subheader.font-style", "bold");
        props.put("header.horizontal-alignment", "center");
        props.put("header.font-style", "bold");
        props.put("header.cell-background", "black");
        
        ExcelExporter.ExportAppender    exportAppender      = new ExcelExporter(props).getAppender();
        
        exportAppender.appendTable("New Sheet", 1, getExcelContent(file));
        
        return exportAppender;
    }
    
    private static SingleValueTableModel getExcelContent(BinaryContent file)
    {
        SingleValueTableModel model = new SingleValueTableModel(); // TO-DO Converting To Excel
        model.addCell(0, 0, new SingleValueTableModel.CellModel(file.getName(), ""));
        
        return model;
    }

    @Override
    public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
    {
        super.validate(process, submission, exceptions, params);
        
        TestInput    testAnalysis    = (TestInput) process.getAttribute("TestAnalysis");

        Debug.assertion(testAnalysis != null, "Test Analysis is null while Processing CSV File.");
        
        if(testAnalysis.getCSV() != null)
        {
            BusinessObjectParser.assertFieldCondition(SUPPORTED_TYPES.contains(testAnalysis.getCSV().getContentType()), testAnalysis, TestInput.FIELD_CSV, "invalid", exceptions, true, submission.getRequest());
        }
    }
}
