using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PDFlib_dotnet;

namespace hello.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HelloController : ControllerBase
    {

        private readonly ILogger<HelloController> _logger;

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

        [HttpGet]
        public IActionResult Get()
        {
            PDFlib p = null;
            byte[] buf;
            /* This is where the data files are. Adjust as necessary. */
            string searchpath = "../../../data";
            HttpResponseMessage result = new HttpResponseMessage();

            try 
            {
                p = new PDFlib();

                // This means we must check return values of load_font() etc.
                p.set_option("errorpolicy=return");

                // Set the search path for font files 
                p.set_option("SearchPath={{" + searchpath +"}}");

                p.begin_document("", "");
                p.set_info("Creator", "hello.cs");
                p.set_info("Author", "Rainer Schaaf");
                p.set_info("Title", "Hello World (ASP.NET/C#)!");

                p.begin_page_ext(0,0, "width=a4.width height=a4.height");

                string fontopt =
                    "fontname=NotoSerif-Regular fontsize=24";

                p.fit_textline("Hello world!", 50, 700, fontopt);
                p.fit_textline("(says ASP.NET/C#)",  50, 676, fontopt);

                p.end_page_ext("");

                p.end_document("");
                buf = p.get_buffer();
                return File(buf, "application/pdf");
            }

            catch (PDFlibException e)
            {
                // caught exception thrown by PDFlib
                return NotFound("PDFlib exception occurred in hello sample:\n" +
                    "[" + e.get_errnum() + "] " + e.get_apiname() +": " +e.get_errmsg()
                    );
            } finally {
                if (p != null) {
                    p.Dispose();
                }
            }
        }
    }
}
