using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace SelectPdf.Samples.Pages
{
    public class SearchPdfTextModel : PageModel
    {
        public void OnGet()
        {

        }

        [BindProperty]
        public string TxtSearchText { get; set; }

        [BindProperty]
        public bool ChkCaseSensitive { get; set; }

        [BindProperty]
        public bool ChkWholeWordsOnly { get; set; }


        public IActionResult OnPost()
        {
            // the test file
            string filePdf = Startup.ServerPath + @"\wwwroot\files\selectpdf.pdf";

            // instantiate a pdf to text converter object
            PdfToText pdfToText = new PdfToText();

            // load PDF file
            pdfToText.Load(filePdf);

            // search for text and retrieve all found text positions
            TextPosition[] positions = pdfToText.Search(TxtSearchText,
                ChkCaseSensitive, ChkWholeWordsOnly);

            // open the existing PDF document in editing mode
            PdfDocument doc = new PdfDocument(filePdf);

            // highlight the found text in the existing PDF document
            for (int i = 0; i < positions.Length; i++)
            {
                TextPosition position = (TextPosition)positions[i];

                PdfPage page = doc.Pages[position.PageNumber - 1];

                PdfRectangleElement rect = new PdfRectangleElement(
                    position.X, position.Y, position.Width, position.Height);
                rect.BackColor = new PdfColor(240, 240, 0);
                rect.Transparency = 30;
                page.Add(rect);
            }

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;

        }
    }
}