using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security;


namespace ImageToPDF
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
        // Set the default output folder
            textBoxSaveFiles.Text = System.IO.Directory.GetCurrentDirectory();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
        // Exit the application
            Close();
        }

        private void btnConvertImages_Click(object sender, EventArgs e)
        {
            // Check to see that user actually has any items in the list
            if (listBoxImages.Items.Count < 1)
            {
                MessageBox.Show("Please add images to the list and try again");
                return;
            }
            
            // Instantiate a PDF Library object
            PDFlibAX.PDFlibrary PDFlib = new PDFlibAX.PDFlibrary(); // A document is created automatically upon creation

            // Iterate through each image filename in the listbox
            bool bFail = false;
            foreach (string sImageFileName in listBoxImages.Items)
            {
                // Create a blank document
                PDFlib.NewDocument();

                // Load the image into memory
                int iImageID;
                if (sImageFileName.Substring(sImageFileName.Length - 3).ToLower() == @"png")
                    iImageID = PDFlib.AddImageFromFile(sImageFileName, 5);
                else
                    iImageID = PDFlib.AddImageFromFile(sImageFileName, 0);

                if (iImageID == 0)
                {
                    MessageBox.Show("PDF Library was unable to load " + sImageFileName);
                    bFail = true;
                    continue;
                }

                // Get width, height of image
                int lWidth = PDFlib.ImageWidth();
                int lHeight = PDFlib.ImageHeight();
                if(PDFlib.SetPageDimensions(lWidth, lHeight)==0)
                {
                    MessageBox.Show("PDF Library was unable to process the page dimensions for " + sImageFileName);
                    bFail = true;
                    continue;
                }

                // Draw the image onto the document using the specified width/height
                if(PDFlib.DrawImage(0, lHeight, lWidth, lHeight)==0)
                {
                    MessageBox.Show("PDF Library was unable to redraw the image " + sImageFileName + " as a PDF file.");
                    bFail = true;
                    continue;
                }

                // Then do so using a .PDF extension instead of the image filename
                // in the output folder...
                string sPDFFileName = textBoxSaveFiles.Text + "\\" + Path.GetFileNameWithoutExtension(sImageFileName) + ".pdf";
                if (PDFlib.SaveToFile(sPDFFileName) == 0)
                {
                    MessageBox.Show("PDF Library could not save the image " + sImageFileName + " as a PDF file.");
                    bFail = true;
                    continue;
                }
            }

        // Let the user know that we're all finished and done
            if (bFail != true)
            {
                MessageBox.Show("The image(s) have been successfully converted to PDF.");
            }
            else
            {
                MessageBox.Show("There was an error converting some images.");
            }
        }
   
        
        private void btnLoadImage_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
            openFileDialog1.Multiselect = true;
            openFileDialog1.Filter = "Image Files (JPEG,GIF,BMP,PNG,TIFF,WMF,EMF)|*.jpg;*.jpeg;*.gif;*.bmp;*.png;*.tif;*.wmf;*.emf";
            openFileDialog1.FilterIndex = 8;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                // Add the selected item to the listbox
                string[] sFileNames = openFileDialog1.FileNames;

                foreach (var item in sFileNames)
                {
                    listBoxImages.Items.Add(item);
                }
            }
        }

        private void btnRemoveImage_Click(object sender, EventArgs e)
        {
            listBoxImages.Items.Remove(listBoxImages.SelectedItem);
        }

        private void btnOutputFolder_Click(object sender, EventArgs e)
        {

            FolderBrowserDialog openFolderDialog1 = new FolderBrowserDialog();
            openFolderDialog1.SelectedPath = System.IO.Directory.GetCurrentDirectory();
            openFolderDialog1.Description = "Select the output folder";

            if (openFolderDialog1.ShowDialog() == DialogResult.OK)
            {
                textBoxSaveFiles.Text = openFolderDialog1.SelectedPath;
            }
        }


        private void btnMerge_Click(object sender, EventArgs e)
        {
            // Check to see that user actually has any items in the list
            if (listBoxImages.Items.Count < 2) // you need at least 2 images in order to merge files
            {
                MessageBox.Show("You need at least 2 images in order to convert and merge.");
                return;
            }

            // Instantiate a PDF Library object
            PDFlibAX.PDFlibrary PDFlib = new PDFlibAX.PDFlibrary(); // A document is created automatically upon creation

            int iDocID = PDFlib.SelectedDocument(); // Get the ID of the first document

            // Iterate through each image filename in the listbox
            bool bFail = false;
            foreach (string sImageFileName in listBoxImages.Items)
            {
                // Create a blank document
                int iNewDocID = PDFlib.NewDocument();

                // Load the image into memory
                int iImageID;
                if (sImageFileName.Substring(sImageFileName.Length - 3).ToLower() == @"png")
                    iImageID = PDFlib.AddImageFromFile(sImageFileName, 5);
                else
                    iImageID = PDFlib.AddImageFromFile(sImageFileName, 0);

                if (iImageID == 0)
                {
                    MessageBox.Show("PDF Library was unable to load " + sImageFileName);
                    bFail = true;
                    continue;
                }

                // Get width, height of image
                int lWidth = PDFlib.ImageWidth();
                int lHeight = PDFlib.ImageHeight();
                if (PDFlib.SetPageDimensions(lWidth, lHeight) == 0)
                {
                    MessageBox.Show("PDF Library was unable to process the page dimensions for " + sImageFileName);
                    bFail = true;
                    continue;
                }

                // Draw the image onto the document using the specified width/height
                if (PDFlib.DrawImage(0, lHeight, lWidth, lHeight) == 0)
                {
                    MessageBox.Show("PDF Library was unable to redraw the image " + sImageFileName + " as a PDF file.");
                    bFail = true;
                    continue;
                }

                // Append the new document to the primary 
                PDFlib.SelectDocument(iDocID);
                PDFlib.MergeDocument(iNewDocID); // Note: the merge function also deletes the new document
            }

            // Delete the first page (blank) of the merged document as this was created by the first
            PDFlib.DeletePages(1, 1); // instance of PDF Library

            // Now all documents have been merged 
            // with the primary document
            // So time to save it...
            if (PDFlib.SaveToFile(textBoxSaveFiles.Text + "\\mergedfile.pdf") == 0) // Use the same folder, and a hard-coded filename
            {
                MessageBox.Show("PDF Library could not save the combined image as a PDF file.");
                bFail = true;
                return; // if that didn't work then forgetaboutit
            }

            // Let the user know that we're all finished and done
            if (bFail != true)
            {
                MessageBox.Show("The image(s) have been successfully merged.");
            }
            else
            {
                MessageBox.Show("There was an error merged the image.");
            }
        }

        private void VisitLink()
        {
            // Change the color of the link text by setting LinkVisited 
            // to true.
            linkLabel1.LinkVisited = true;
            //Call the Process.Start method to open the default browser 
            //with a URL:
            System.Diagnostics.Process.Start("https://www.loslab.com/pdf-library/delphi-pdf-library");
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                VisitLink();
            }
            catch (Exception)
            {
                MessageBox.Show("Unable to open link that was clicked.");
            }
        }

        private void textBoxSaveFiles_TextChanged(object sender, EventArgs e)
        {

        }
    }
}