using System;
using System.Collections.Generic;
using System.Text;

using ExpertPdf;

namespace pdftotextcmd
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                InvalidArguments();
                return;
            }

            // the source PDF document
            string srcPdfFile = null;
            // set the output text layout
            TextLayout layout = TextLayout.OriginalLayout;
            // mark page breaks with the PdfToTextConverter.PAGE_BREAK_MARK character
            bool markPageBreaks = false;
            // output the text in a HTML file and 
            // add meta tags with PDF document description
            bool addHtmlMetaTags = false;
            // the user password to open the PDF document 
            string userPassword = null;

            // parse arguments
            for (int argIdx = 0; argIdx < args.Length; argIdx++)
            {
                string argument = args[argIdx];

                // get the input PDF document
                if (argument.StartsWith("/pdf:"))
                {
                    string pdfFilePath = argument.Substring("/pdf:".Length, argument.Length - "/pdf:".Length);
                    pdfFilePath = RemoveQuotes(pdfFilePath).Trim();
                    if (pdfFilePath != null && pdfFilePath.Length > 0)
                    {
                        srcPdfFile = pdfFilePath;
                    }
                    else
                    {
                        Console.WriteLine("Invalid source pdf file name.");
                        InvalidArguments();
                        return;
                    }
                }

                // get the PDF document password
                if (argument.StartsWith("/userpswd:"))
                {
                    string userPasswordStr = argument.Substring("/userpswd:".Length, argument.Length - "/userpswd:".Length);


                    if (userPasswordStr != null)
                    {
                        userPassword = userPasswordStr;
                    }
                }

                // get the output text layout
                if (argument.StartsWith("/layout:"))
                {
                    string layoutStr = argument.Substring("/layout:".Length, argument.Length - "/layout:".Length);


                    if (layoutStr.ToLower().Equals("reading"))
                    {
                        layout = TextLayout.ReadingLayout;
                    }
                    else if (layoutStr.ToLower().Equals("original"))
                    {
                        layout = TextLayout.OriginalLayout;
                    }
                    else
                    {
                        Console.WriteLine("Invalid layout format.");
                        InvalidArguments();
                        return;
                    }
                }

                // check if mark page breaks option
                if (argument == "/pagebreaks")
                {
                    markPageBreaks = true;
                }

                // check if the output text is in a html format
                if (argument == "/html")
                {
                    addHtmlMetaTags = true;
                }
            }

            if (srcPdfFile == null)
            {
                Console.WriteLine("The source pdf file is not specified.");
                InvalidArguments();
                return;
            }

            // create pdf to text converter
            PdfToTextConverter pdfToTextConverter = new PdfToTextConverter();
            // set converter options
            pdfToTextConverter.Layout = layout;
            pdfToTextConverter.MarkPageBreaks = markPageBreaks;
            pdfToTextConverter.AddHtmlMetaTags = addHtmlMetaTags;
            pdfToTextConverter.UserPassword = userPassword;

            // Note: If the license key is not set or a demo license key is set 
            // only the first page from the document is converted to text.
            // In order to get a full version for a limited period please set the 
            // license key received after the product download

            //pdfToTextConverter.LicenseKey = "put your license key here";

            string outFileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(srcPdfFile),
                    System.IO.Path.GetFileNameWithoutExtension(srcPdfFile));

            if (addHtmlMetaTags)
                outFileName += ".html";
            else
                outFileName += ".txt";

            try
            {
                // extract text from PDF
                string extractedText = pdfToTextConverter.ConvertToText(srcPdfFile);
                // write the resulted string into an output file in the working directory using UTF-8 encoding
                System.IO.File.WriteAllText(outFileName, extractedText, System.Text.Encoding.UTF8);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public static string RemoveQuotes(string quotedString)
        {
            string res = quotedString;
            if (res.StartsWith("\""))
            {
                res = res.Substring(1, res.Length - 1);
            }
            if (res.EndsWith("\""))
            {
                res = res.Substring(0, res.Length - 1);
            }

            return res;
        }

        private static void InvalidArguments()
        {
            Console.WriteLine(@"Usage: pdftotextcmd.exe /pdf:source_pdf_file [/layout:reading|original] [/pagebreaks] [/html] [/userpswd:user_password]");
            Console.WriteLine(String.Format(@"Example: pdftotextcmd.exe /pdf:source_file.pdf"));
        }
    }
}
