
using Microsoft.AspNetCore.Mvc;
using DevExpress.XtraReports.UI;
using DevExpress.XtraReports.Web.Extensions;
using System.IO;

namespace MTWorkHR.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ReportController : ControllerBase
    {
        private readonly ReportStorageWebExtension _reportStorage;

        public ReportController(ReportStorageWebExtension reportStorage)
        {
            _reportStorage = reportStorage;
        }

        [HttpGet("generate-pdf")]
        public async Task<IActionResult> GeneratePdf(string reportUrl)
        {
            byte[] reportData = _reportStorage.GetData(reportUrl);

            // Load the report from the byte array
            using (MemoryStream ms = new MemoryStream(reportData))
            {
                XtraReport report = XtraReport.FromStream(ms, true);

                using (MemoryStream pdfStream = new MemoryStream())
                {
                    try
                    {
                        if (report.DataSource == null)
                        {
                            var m = "The report's DataSource is null.";
                        }
                        await report.CreateDocumentAsync();

                        await report.ExportToPdfAsync(pdfStream);
                    }
                    catch(Exception e)
                    {
                        var mess = e.Message;
                    }
                    return File(pdfStream.ToArray(), "application/pdf", "GeneratedReport.pdf");
                }
            }
        }

    }
}
