using ComPDFKit.PDFDocument;
using System;
using System.Windows;

namespace Compdfkit_Tools.Common
{
    /// <summary>
    /// Interaction logic for PasswordWindow.xaml
    /// </summary>
    public partial class PasswordWindow : Window
    {
        private CPDFDocument pdfDoc;

        public delegate void DialogCloseEventHandler(object sender, PasswordEventArgs e);
        public event DialogCloseEventHandler DialogClosed;

        public PasswordWindow()
        {
            InitializeComponent();
        }

        private void PasswordDialog_Loaded(object sender, RoutedEventArgs e)
        {
            PasswordDialog.Canceled += PasswordDialog_Canceled;
            PasswordDialog.Confirmed += PasswordDialog_Confirmed;
            PasswordDialog.Closed += PasswordDialog_Closed;
        }

        public void InitDocument(CPDFDocument pdfDoc)
        {
            this.pdfDoc = pdfDoc;
        }

        private void PasswordDialog_Unloaded(object sender, RoutedEventArgs e)
        {
            PasswordDialog.Canceled -= PasswordDialog_Canceled;
            PasswordDialog.Confirmed -= PasswordDialog_Confirmed;
            PasswordDialog.Closed -= PasswordDialog_Closed;
        }

        private void PasswordDialog_Closed(object sender, EventArgs e)
        {
            PasswordEventArgs passwordEventArgs = new PasswordEventArgs(string.Empty);
            CloseWindow(passwordEventArgs);
        }

        private void PasswordDialog_Confirmed(object sender, string e)
        {
            if (pdfDoc != null)
            {
                pdfDoc.UnlockWithPassword(e);
                if (pdfDoc.IsLocked == false)
                {
                    PasswordEventArgs passwordEventArgs = new PasswordEventArgs(e);
                    CloseWindow(passwordEventArgs);
                }
                else
                {
                    PasswordDialog.SetShowError("Wrong Password", Visibility.Visible);
                }
            }
        }

        private void PasswordDialog_Canceled(object sender, EventArgs e)
        {
            PasswordEventArgs passwordEventArgs = new PasswordEventArgs(string.Empty);
            CloseWindow(passwordEventArgs);
        }

        // The processing logic when the pop-up window is closed
        private void CloseWindow(PasswordEventArgs dialogResult)
        {
            // Trigger the close event and pass the return value
            DialogClosed?.Invoke(this, dialogResult);

            // Close the pop-up window
            Close();
        }
    }

    public class PasswordEventArgs : EventArgs
    {
        public string DialogResult { get; set; }

        public PasswordEventArgs(string dialogResult)
        {
            DialogResult = dialogResult;
        }
    }
}
