package com.sn.sowsysrestapi.domain.infrastructure.service.report;

import com.sn.sowsysrestapi.domain.repository.ReportRepo;
import com.sn.sowsysrestapi.domain.service.IssuePdfReportService;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Locale;

@Service
public class PdfReportService implements IssuePdfReportService {

    @Autowired
    private IssuePdfReportService issuePdfReportService;

    @Autowired
    private ReportRepo reportRepo;

    @Override
    public byte[] issuePdfReport(String userCode, LocalDate startDate, LocalDate endDate) {

        try {
//            var inputStream = this.getClass().getResourceAsStream("/reports/sow-report.jasper");
            var inputStream = this.getClass().getResourceAsStream("");

            var parameters = new HashMap<String, Object>();
            parameters.put("REPORT_LOCALE", new Locale("en-us", "USA"));

            Long reportDirectoryId = reportRepo.getReportDirectoryId(userCode);

            var sowReports = reportRepo.findByReportDirectoryAndStartDateAndEndDate(
                    reportDirectoryId, startDate, endDate);

            var dataSource = new JRBeanCollectionDataSource(sowReports);


            var jasperPrint = JasperFillManager.fillReport(inputStream, parameters, dataSource);

            return JasperExportManager.exportReportToPdf(jasperPrint);

        } catch (Exception e) {
            throw new ReportException("It was not possible to issue the report at this time.", e);
        }

    }
}
