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

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

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

        public List<SelectListItem> TextLayouts { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Original", Text = "Original (Keep Positions)" },
            new SelectListItem { Value = "Reading", Text = "Reading (Reading Order)" },
        };

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

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

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

            // settings
            string text_layout = DdlTextLayout;
            TextLayout textLayout = (TextLayout)Enum.Parse(typeof(TextLayout),
                text_layout, true);

            int startPage = 1;
            try
            {
                startPage = Convert.ToInt32(TxtStartPage);
            }
            catch { }

            int endPage = 0;
            try
            {
                endPage = Convert.ToInt32(TxtEndPage);
            }
            catch { }

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

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

            // set the properties
            pdfToText.Layout = textLayout;
            pdfToText.StartPageNumber = startPage;
            pdfToText.EndPageNumber = endPage;

            // extract the text
            string text = pdfToText.GetText();

            // convert text to UTF-8 bytes
            byte[] utf8 = System.Text.Encoding.UTF8.GetBytes(text);

            // return resulted text file
            FileResult fileResult = new FileContentResult(utf8,
                "text/plain; charset=UTF-8");
            fileResult.FileDownloadName = "output.txt";
            return fileResult;

        }
    }
}