using DevExpress.XtraReports.UI;
using Microsoft.AspNetCore.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace MTWorkHR.Infrastructure.Reports
{
    public class CustomReportStorageWebExtension : DevExpress.XtraReports.Web.Extensions.ReportStorageWebExtension
    {
      //  private readonly GlobalInfo globalInfo;
    //    private readonly AppSettingsConfiguration settings;
        public CustomReportStorageWebExtension()
        {
        }
        public override byte[] GetData(string url)
        {
            try
            {
                string[] parts = url.Split('?');
                string reportName = parts[0];
                string parametersQueryString = parts.Length > 1 ? parts[1] : string.Empty;

                XtraReport report = getReport(reportName);
                if (report == null)
                {
                    throw new DevExpress.XtraReports.Web.ClientControls.FaultException($"Could not find report '{url}'.");
                }

                // Apply report parameters
                var parameters = HttpUtility.ParseQueryString(parametersQueryString);
                foreach (string parameterName in parameters.AllKeys)
                {
                    if (!string.IsNullOrEmpty(parameters.Get(parameterName)) && parameters.Get(parameterName) != "null")
                    {
                        report.Parameters[parameterName].Value = Convert.ChangeType(parameters.Get(parameterName), report.Parameters[parameterName].Type);
                    }
                }

                report.CreateDocument(); // Ensure the report document is created

                using (MemoryStream ms = new MemoryStream())
                {
                    report.ExportToPdf(ms);  // Export to PDF
                    return ms.ToArray();
                }
            }
            catch (Exception ex)
            {
                throw new DevExpress.XtraReports.Web.ClientControls.FaultException($"Error generating report '{url}': {ex.Message}", ex);
            }
        }

        private XtraReport getReport(string reportName)
        {
            switch (reportName)
            {
                case "ContractReport":
                case "contractreport":
                case "contractReport":
                    return new ContractReport();
                case "ContractAllowance":
                    return new ContractAllowances();
                default: return null;
            }
        }
    
    }
}
