using System.Diagnostics;
using System.IO;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ZPDuszynska.Models;

namespace ZPDuszynska.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        [Authorize]
        public IActionResult Nekrologi()
        {
            Nekrolog1Model model = new Nekrolog1Model();
            model.Line1_1 = "Z głębokim żalem zawiadamiamy, że dnia ";
            model.Line1_2 = "1 stycznia ";
            model.Line1_3 = "2025 roku";

            model.Line2_1 = "odszedł od nas na zawsze w wieku ";
            model.Line2_2 = "66 ";
            model.Line2_3 = "lat";

            model.Line3_1 = "ŚP. ";
            model.Line3_2 = "JAN";

            model.Line4_1 = "KOWALSKI";

            model.Line11_1 = "";
            model.Line11_2 = "";

            model.Line5_1 = "Dom Żałoby: ";

            model.Line6_1 = "Wystawienie Zmarłego w Kościele o godz. ";
            model.Line6_2 = "13.30";

            model.Line7_1 = "Msza Święta Żałobna odprawiona zostanie w Kościele w Milejowie";

            model.Line8_1 = "dnia ";
            model.Line8_2 = "8 marca ";
            model.Line8_3 = "2025r. (";
            model.Line8_4 = "sobota";
            model.Line8_5 = ") o godz. ";
            model.Line8_6 = "14.00";
            model.Line8_7 = ", po której nastąpi";

            model.Line9_1 = "odprowadzenie Zmarłego na miejscowy cmentarz rzymskokatolicki";

            model.Line10_1 = "Pogrążona w smutku ";
            model.Line10_2 = "NAJBLIŻSZA RODZINA";


            return View(model);
        }

        [HttpPost]
        [Authorize]
        public ActionResult Nekrologi(Nekrolog1Model model)
        {
            string inputPath = "nekrolog_template.pdf";

            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(inputPath);
            Rectangle size = reader.GetPageSizeWithRotation(1);
            iTextSharp.text.Document document = new iTextSharp.text.Document(size);
            MemoryStream ms = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            document.Open();

            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage page = writer.GetImportedPage(reader, 1);
            cb.AddTemplate(page, 0, 0);

            MyTextLine l1 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line1_1, fontBold = false, fontSize = 34 },
    new MyText { text = model.Line1_2, fontBold = true, fontSize = 34 },
    new MyText { text = model.Line1_3, fontBold = false, fontSize = 34 } }
            };
            MyTextLine l2 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line2_1, fontBold = false, fontSize = 34 },
    new MyText { text = model.Line2_2, fontBold = true, fontSize = 44 },
    new MyText { text = model.Line2_3, fontBold = false, fontSize = 34 } }
            };
            MyTextLine l3 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line3_1, fontBold = false, fontSize = 50 },
    new MyText { text = model.Line3_2, fontBold = true, fontSize = 90 } }
            };
            MyTextLine l5 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line5_1, fontBold = false, fontSize = 32 } }
            };
            MyTextLine l6 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line6_1, fontBold = false, fontSize = 32 },
    new MyText { text = model.Line6_2, fontBold = true, fontSize = 32 } }
            };
            MyTextLine l7 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line7_1, fontBold = false, fontSize = 32 } }
            };
            MyTextLine l8 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line8_1, fontBold = false, fontSize = 32 },
    new MyText { text = model.Line8_2, fontBold = true, fontSize = 32 },
    new MyText { text = model.Line8_3, fontBold = false, fontSize = 32 },
    new MyText { text = model.Line8_4, fontBold = true, fontSize = 32 },
    new MyText { text = model.Line8_5, fontBold = false, fontSize = 32 },
    new MyText { text = model.Line8_6, fontBold = true, fontSize = 32 },
    new MyText { text = model.Line8_7, fontBold = false, fontSize = 32 } }
            };
            MyTextLine l9 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line9_1, fontBold = false, fontSize = 32 } }
            };
            MyTextLine l10 = new MyTextLine
            {
                texts = new List<MyText>() {
    new MyText { text = model.Line10_1, fontBold = false, fontSize = 20 },
    new MyText { text = model.Line10_2, fontBold = true, fontSize = 20 } }
            };

            if (!string.IsNullOrWhiteSpace(model.Line11_1+model.Line11_2))
            {
                MyTextLine l4 = new MyTextLine
                {
                    texts = new List<MyText>() {
        new MyText { text = model.Line4_1, fontBold = true, fontSize = 110 } }
                };
                MyTextLine l11 = new MyTextLine
                {
                    texts = new List<MyText>() {
        new MyText { text = model.Line11_1, fontBold = false, fontSize = 30 },
        new MyText { text = model.Line11_2, fontBold = true, fontSize = 40 } }
                };
                AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 415, 700, l4);
                AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 290, 700, l11);
            }
            else
            {
                MyTextLine l4 = new MyTextLine
                {
                    texts = new List<MyText>() {
        new MyText { text = model.Line4_1, fontBold = true, fontSize = 150 } }
                };
                AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 415, 700, l4);
            }

            AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 550, 700, l1);
            AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 523, 700, l2);
            AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 490, 600, l3);
            AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 240, 700, l5);
            AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 215, 700, l6);
            AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 190, 700, l7);
            AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 165, 700, l8);
            AddTextToPdf(cb, PdfPCell.ALIGN_CENTER, 70, 140, 700, l9);
            AddTextToPdf(cb, PdfPCell.ALIGN_RIGHT, 70, 102, 720, l10);

            document.Close();
            var result = ms.ToArray();

            ms.Close();
            writer.Close();
            reader.Close();

            Response.Headers["Content-Disposition"] = "inline; filename=Nekrolog.pdf";
            return File(result.ToArray(), "application/pdf");
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        void AddTextToPdf(PdfContentByte cb, int align, int x, int y, int width, MyTextLine line)
        {
            var timesFontPath = "times.ttf";
            var timesbdFontPath2 = "timesbd.ttf";

            BaseFont bf = BaseFont.CreateFont(timesFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            BaseFont bf2 = BaseFont.CreateFont(timesbdFontPath2, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Color bc = new Color(00, 00, 00);

            PdfPTable table = new PdfPTable(1);

            float textWidth = 0;
            foreach (var l in line.texts)
            {
                Font f = new Font(bf, l.fontSize - 5, Font.NORMAL, bc);
                Font fb = new Font(bf2, l.fontSize - 5, Font.BOLD, bc);
                if (l.fontBold)
                {
                    l.c = new Chunk(l.text, fb);
                    textWidth += bf2.GetWidthPoint(l.text, l.fontSize - 5);
                }
                else
                {
                    l.c = new Chunk(l.text, f);
                    textWidth += bf.GetWidthPoint(l.text, l.fontSize - 5);
                }
            }

            float scaleValue = (textWidth > width) ? (width / textWidth) * 100 : 100;

            Phrase texttoInsertttttt = new Phrase();
            foreach (var l in line.texts)
            {
                l.c.SetHorizontalScaling(scaleValue / 100);
                texttoInsertttttt.Add(l.c);
            }

            PdfPCell cell = new PdfPCell(texttoInsertttttt);
            cell.Rowspan = 1;
            cell.HorizontalAlignment = align;
            cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
            cell.NoWrap = true;
            //    cell.MinimumHeight = height;
            //    cell.FixedHeight = height;
            cell.Border = PdfPCell.NO_BORDER;
            table.AddCell(cell);
            table.TotalWidth = width;
            table.WriteSelectedRows(0, -1, x, y, cb);
        }
    }
}
