using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using O2S.Components.PDFView4NET;

namespace FileAttachments
{
    public partial class MainPage : UserControl
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MainPage"/> class.
        /// </summary>
        public MainPage()
        {
            InitializeComponent();
            DataContext = this;
        }

        /// <summary>
        /// Handles the Click event of the Browse control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Browse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog browseFile = new OpenFileDialog();
            browseFile.Multiselect = false;
            browseFile.Filter = "PDF Files (*.pdf)|*.pdf";

            bool? result = browseFile.ShowDialog();

            if (result is bool && (bool)result)
            {
                PdfControl.Document = new PDFDocument();
                PdfControl.Document.Load(browseFile.File.OpenRead());
                FilePathTextBox.Text = browseFile.File.Name;
                RefreshItemsSource();
            }
        }

        /// <summary>
        /// Refreshes the items source.
        /// </summary>
        private void RefreshItemsSource()
        {
            DetailsListBox.ItemsSource = null;
            DetailsListBox.ItemsSource = FileAttachments;
        }

        private List<PDFFileAttachment> _pdfFileAttachments = new List<PDFFileAttachment>();

        /// <summary>
        /// Gets or sets the file attachments.
        /// </summary>
        /// <value>
        /// The file attachments.
        /// </value>
        public List<PDFFileAttachment> FileAttachments
        {
            get
            {
                _pdfFileAttachments.Clear();
                foreach (PDFFileAttachment pdfFileAttachment in PdfControl.Document.FileAttachments)
                {
                    _pdfFileAttachments.Add(pdfFileAttachment);
                }

                return _pdfFileAttachments;
            }
        }

        private Popup _popup = new Popup();

        /// <summary>
        /// Handles the Click event of the AddAttachment control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void AddAttachment_Click(object sender, RoutedEventArgs e)
        {
            EditAttachmentForm eaf = new EditAttachmentForm() { Width = this.ActualWidth, Height = this.ActualHeight };
            _popup.Child = eaf;
            eaf.Closed += new EventHandler(eaf_Add_Closed);
            _popup.IsOpen = true;
        }

        /// <summary>
        /// Handles the Closed event of the eaf control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void eaf_Add_Closed(object sender, EventArgs e)
        {
            EditAttachmentForm eaf = _popup.Child as EditAttachmentForm;

            if (eaf != null)
            {
                eaf.Closed -= new EventHandler(eaf_Add_Closed);

                if (eaf.AddAttachment)
                {
                    // Read the file in a byte array.
                    FileStream fs = eaf.FileStream;
                    byte[] fileData = new byte[fs.Length];
                    fs.Read(fileData, 0, fileData.Length);
                    fs.Close();

                    // Create a file attachment object and add it to document.
                    PDFFileAttachment fileAttachment = new PDFFileAttachment();
                    fileAttachment.Data = fileData;
                    fileAttachment.Description = eaf.Description;
                    fileAttachment.FileName = eaf.FileName;
                    PdfControl.Document.FileAttachments.Add(fileAttachment);
                }
                
                _popup.IsOpen = false;
                _popup.Child = null;
                RefreshItemsSource();
            }
        }

        /// <summary>
        /// Handles the Click event of the EditDescription control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void EditDescription_Click(object sender, RoutedEventArgs e)
        {
            PDFFileAttachment selectedAttachment = DetailsListBox.SelectedItem as PDFFileAttachment;

            if (selectedAttachment != null)
            {
                EditAttachmentForm eaf = new EditAttachmentForm() { Width = this.ActualWidth, Height = this.ActualHeight };
                eaf.BrowseButton.IsEnabled = false;
                eaf.FileName = selectedAttachment.FileName;
                eaf.Description = selectedAttachment.Description;
                _popup.Child = eaf;
                eaf.Closed += new EventHandler(eaf_Modify_Closed);
                _popup.IsOpen = true;
            }
        }

        private void eaf_Modify_Closed(object sender, EventArgs e)
        {
            EditAttachmentForm eaf = _popup.Child as EditAttachmentForm;

            if (eaf != null)
            {
                eaf.Closed -= new EventHandler(eaf_Modify_Closed);

                if (eaf.AddAttachment && DetailsListBox.SelectedItem != null)
                {
                    PDFFileAttachment selectedAttachment = DetailsListBox.SelectedItem as PDFFileAttachment;
                    selectedAttachment.Description = eaf.Description;
                    RefreshItemsSource();
                }

                _popup.IsOpen = false;
                _popup.Child = null;
            }
        }

        /// <summary>
        /// Handles the Click event of the SaveAttachment control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void SaveAttachment_Click(object sender, RoutedEventArgs e)
        {
            PDFFileAttachment selectedAttachment = DetailsListBox.SelectedItem as PDFFileAttachment;

            if (selectedAttachment != null)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Any Files (*.*)|*.*";
                bool? result = sfd.ShowDialog();

                if (result is bool && (bool)result)
                {
                    System.IO.Stream stream = sfd.OpenFile();
                    byte[] fileData = selectedAttachment.Data;
                    stream.Write(fileData, 0, fileData.Length);
                    stream.Flush();
                    stream.Close();
                    RefreshItemsSource();
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the RemoveAttachment control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void RemoveAttachment_Click(object sender, RoutedEventArgs e)
        {
            PDFFileAttachment selectedAttachment = DetailsListBox.SelectedItem as PDFFileAttachment;

            if (selectedAttachment != null)
            {
                MessageBoxResult result = MessageBox.Show("Are you sure you want to delete the selected attachment?",
                    "PDFView4NET", MessageBoxButton.OKCancel);

                if (result == MessageBoxResult.OK)
                {
                    PdfControl.Document.FileAttachments.Remove(selectedAttachment);
                    RefreshItemsSource();
                }
            }
        }

        /// <summary>
        /// Handles the Click event of the SaveDocument control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void SaveDocument_Click(object sender, RoutedEventArgs e)
        {
            if (PdfControl.Document != null && PdfControl.Document.PageCount > 0)
            {
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.Filter = "PDF Files (*.pdf)|*.pdf";
                bool? result = saveDialog.ShowDialog();

                if (result is bool && (bool)result)
                {
                    System.IO.Stream stream = saveDialog.OpenFile();
                    PdfControl.Document.Save(stream);
                    stream.Close();
                }
            }
            else
            {
                MessageBox.Show("Nothing to save.", "Message", MessageBoxButton.OK);
            }
        }
    }
}