using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Diagnostics;

namespace WorkFlowCheck.BL.DocumentGenerator
{
    public class DokumentumGenerator
    {
        public static byte[] DocxToPdfL(byte[] wordBytes, List<string> imagePaths = null)
        {
            string pdfDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Pdf");
            string fileName = Guid.NewGuid().ToString();

            string tempWordPath = Path.Combine(pdfDirectory, fileName + ".docx");
            string tempPdfPath = Path.Combine(pdfDirectory, fileName + ".pdf");

            try
            {
                // Word fájl mentése ideiglenes fájlba
                File.WriteAllBytes(tempWordPath, wordBytes);

                if (imagePaths != null && imagePaths.Count > 0)
                {
                    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(tempWordPath, true))
                    {
                        MainDocumentPart mainPart = wordDoc.MainDocumentPart;
                        foreach (string imagePath in imagePaths)
                        {
                            if (File.Exists(imagePath))
                            {
                                InsertImageAsNewPage(mainPart, imagePath);
                            }
                        }

                        wordDoc.MainDocumentPart.Document.Save();
                    }
                }


                // LibreOffice parancssori konverzió
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
#if !DEBUG
                    FileName = "e:\\LibreOffice\\program\\soffice", // LibreOffice parancs
#else
                    FileName = "c:\\Program Files\\LibreOffice\\program\\soffice", // LibreOffice parancs
#endif
                    Arguments = $"--headless --convert-to pdf \"{tempWordPath}\" --outdir \"{pdfDirectory}",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                using (Process process = Process.Start(startInfo))
                {
                    process.WaitForExit();
                }

                // Ellenőrzés, hogy létrejött-e a PDF
                if (File.Exists(tempPdfPath))
                {
                    byte[] pdfBytes = File.ReadAllBytes(tempPdfPath);

                    // Ideiglenes fájlok törlése
                    File.Delete(tempWordPath);
                    File.Delete(tempPdfPath);

                    return pdfBytes;
                }
                else
                {
                    throw new Exception("PDF konverzió sikertelen.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Hiba a PDF konverzió során: " + ex.Message);
                return null;
            }
        }
        private static void InsertImageAsNewPage(MainDocumentPart mainPart, string imagePath)
        {
            string fileName = Path.GetFileName(imagePath);

            // Kép méretezés – max szélesség/magasság A4 hasznos területhez igazítva
            using var image = SixLabors.ImageSharp.Image.Load(imagePath);
            int pixelWidth = image.Width;
            int pixelHeight = image.Height;

            long maxWidth = 5760000L;   // kb. 16 cm
            long maxHeight = 7200000L;  // kb. 20 cm

            double aspectRatio = (double)pixelHeight / pixelWidth;
            long finalWidth = maxWidth;
            long finalHeight = (long)(maxWidth * aspectRatio);

            if (finalHeight > maxHeight)
            {
                finalHeight = maxHeight;
                finalWidth = (long)(maxHeight / aspectRatio);
            }

            // Kép hozzáadása Word dokumentumhoz
            ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
            using (FileStream stream = new FileStream(imagePath, FileMode.Open))
            {
                imagePart.FeedData(stream);
            }

            string imagePartId = mainPart.GetIdOfPart(imagePart);
            Drawing drawing = CreateImageDrawing(imagePartId, finalWidth, finalHeight);

            // Kép beillesztése középre igazítva
            Paragraph imageParagraph = new Paragraph(new Run(drawing))
            {
                ParagraphProperties = new ParagraphProperties(
                    new Justification() { Val = JustificationValues.Center }
                )
            };

            TableCell imageCell = new TableCell(imageParagraph,
                new TableCellProperties(
                    new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center },
                    new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "10000" }
                ));

            // Képes sor (magas, kitölti az oldalt)
            TableRow imageRow = new TableRow(imageCell);
            imageRow.AppendChild(new TableRowProperties(
                new TableRowHeight() { Val = 9000, HeightType = HeightRuleValues.Exact }
            ));

            // Fájlnév beillesztése középre
            Paragraph fileNamePara = new Paragraph(new Run(new Text(fileName)))
            {
                ParagraphProperties = new ParagraphProperties(
                    new Justification() { Val = JustificationValues.Center }
                )
            };

            TableCell fileNameCell = new TableCell(fileNamePara,
                new TableCellProperties(
                    new TableCellVerticalAlignment { Val = TableVerticalAlignmentValues.Center },
                    new TableCellWidth() { Type = TableWidthUnitValues.Pct, Width = "10000" }
                ));

            // Fájlnév sor (normál magasság)
            TableRow fileNameRow = new TableRow(fileNameCell);
            fileNameRow.AppendChild(new TableRowProperties(
                new TableRowHeight() { Val = 400, HeightType = HeightRuleValues.Auto }
            ));

            // Táblázat – szegély nélkül, teljes oldalszélességben
            Table table = new Table(
                new TableProperties(
                    new TableWidth { Width = "10000", Type = TableWidthUnitValues.Pct },
                    new TableBorders(
                        new TopBorder { Val = BorderValues.None },
                        new BottomBorder { Val = BorderValues.None },
                        new LeftBorder { Val = BorderValues.None },
                        new RightBorder { Val = BorderValues.None },
                        new InsideHorizontalBorder { Val = BorderValues.None },
                        new InsideVerticalBorder { Val = BorderValues.None }
                    )
                ),
                imageRow,
                fileNameRow
            );

            // Új oldal és a táblázat beszúrása a dokumentum végére
            Body body = mainPart.Document.Body;
            body.Append(new Paragraph(new Run(new Break() { Type = BreakValues.Page })));
            body.Append(table);
        }
        private static Drawing CreateImageDrawing(string relationshipId, long width, long height)
        {
            return new Drawing(
                new DocumentFormat.OpenXml.Drawing.Wordprocessing.Inline(
                    new DocumentFormat.OpenXml.Drawing.Wordprocessing.Extent() { Cx = width, Cy = height },
                    new DocumentFormat.OpenXml.Drawing.Wordprocessing.EffectExtent()
                    {
                        LeftEdge = 0L,
                        TopEdge = 0L,
                        RightEdge = 0L,
                        BottomEdge = 0L
                    },
                    new DocumentFormat.OpenXml.Drawing.Wordprocessing.DocProperties()
                    {
                        Id = (UInt32Value)1U,
                        Name = "Inserted Image"
                    },
                    new DocumentFormat.OpenXml.Drawing.Graphic(
                        new DocumentFormat.OpenXml.Drawing.GraphicData(
                            new DocumentFormat.OpenXml.Drawing.Pictures.Picture(
                                new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureProperties(
                                    new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualDrawingProperties()
                                    {
                                        Id = (UInt32Value)0U,
                                        Name = "Picture"
                                    },
                                    new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureDrawingProperties()),
                                new DocumentFormat.OpenXml.Drawing.Pictures.BlipFill(
                                    new DocumentFormat.OpenXml.Drawing.Blip()
                                    {
                                        Embed = relationshipId
                                    },
                                    new DocumentFormat.OpenXml.Drawing.Stretch(
                                        new DocumentFormat.OpenXml.Drawing.FillRectangle())),
                                new DocumentFormat.OpenXml.Drawing.Pictures.ShapeProperties(
                                    new DocumentFormat.OpenXml.Drawing.Transform2D(
                                        new DocumentFormat.OpenXml.Drawing.Offset() { X = 0L, Y = 0L },
                                        new DocumentFormat.OpenXml.Drawing.Extents() { Cx = width, Cy = height }),
                                    new DocumentFormat.OpenXml.Drawing.PresetGeometry(
                                        new DocumentFormat.OpenXml.Drawing.AdjustValueList())
                                    { Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle }))
                        )
                        { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                )
                { DistanceFromTop = 0U, DistanceFromBottom = 0U, DistanceFromLeft = 0U, DistanceFromRight = 0U });
        }

    }
}
