using iDiTect.Pdf.Annotations;
using iDiTect.Pdf.DigitalSignatures;
using iDiTect.Pdf.Editing;
using iDiTect.Pdf.InteractiveForms;
using iDiTect.Pdf.IO;
using iDiTect.Pdf.Objects;
using iDiTect.Pdf.Resources;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace iDiTect.Pdf.Demo
{
    public static class SignatureHelper
    {     

        public static void AddTextSignature2PDF()
        {            
            PdfFile pdfFile = new PdfFile();
            PdfDocument document = pdfFile.Import(File.ReadAllBytes("sample.pdf"));
            
            //Input your certificate and password
            X509Certificate2 certificate = new X509Certificate2("test.pfx", "iditect");

            //First you need create a SignatureField with unique name
            SignatureField signatureField = new SignatureField("iDiTect Sign Field");
            //Add signature object to a signature field, so we can add a visualization to it
            signatureField.Signature = new Signature(certificate);
            //Add signature info as need
            signatureField.Signature.Properties.Reason = "Sign by iDiTect";
            signatureField.Signature.Properties.Location = "World Wide Web";
            signatureField.Signature.Properties.ContactInfo = "1234567";

            //Apply a visible signature widiget to represent the contents of the signature field.
            SignatureWidget widget = signatureField.Widgets.AddWidget();
            //Set signature position and size
            widget.Rect = new System.Windows.Rect(new System.Windows.Point(200, 200), new System.Windows.Size(400, 100));
            widget.RecalculateContent();
          
            //Customize signature appearance, you can show all signature info, or just name or date 
            PageContentBuilder signatureAppearance = new PageContentBuilder(widget.Content.NormalContentSource);
            signatureAppearance.Position.Translate(10, 0);
            signatureAppearance.DrawText("Digitally signed by " + certificate.GetNameInfo(X509NameType.SimpleName, true));
            signatureAppearance.Position.Translate(10, 20);
            signatureAppearance.DrawText("Reason: " + signatureField.Signature.Properties.Reason);
            signatureAppearance.Position.Translate(10, 40);
            signatureAppearance.DrawText("Location: " + signatureField.Signature.Properties.Location);
            signatureAppearance.Position.Translate(10, 60);
            signatureAppearance.DrawText("Contact: " + signatureField.Signature.Properties.ContactInfo);
            signatureAppearance.Position.Translate(10, 80);
            signatureAppearance.DrawText("Date: " + DateTime.Now.ToString());

            //Add this signature to first PDF page
            document.Pages[0].Annotations.Add(widget);
            document.AcroForm.FormFields.Add(signatureField);
            
            //Digital sign feature need the stream support reading, so you have to use ReadWrite mode here
            using (FileStream fs = new FileStream("signed.pdf", FileMode.Create, FileAccess.ReadWrite))
            {
                pdfFile.Export(document, fs);
            }

        }

        public static void AddImageSignature2PDF()
        {
            PdfFile pdfFile = new PdfFile();
            PdfDocument document = pdfFile.Import(File.ReadAllBytes("sample.pdf"));

            //Input your certificate and password
            X509Certificate2 certificate = new X509Certificate2("test.pfx", "iditect");

            //First you need create a SignatureField with unique name
            SignatureField signatureField = new SignatureField("iDiTect Sign Field");
            //Add signature object to a signature field, so we can add a visualization to it
            signatureField.Signature = new Signature(certificate);
            //Add signature info as need
            signatureField.Signature.Properties.Reason = "Sign by iDiTect";
            signatureField.Signature.Properties.Location = "World Wide Web";
            signatureField.Signature.Properties.ContactInfo = "1234567";

            //Apply a visible signature widiget to represent the contents of the signature field.
            SignatureWidget widget = signatureField.Widgets.AddWidget();
            //Set signature position and size
            widget.Rect = new System.Windows.Rect(new System.Windows.Point(200, 200), new System.Windows.Size(50, 50));
            widget.RecalculateContent();

            //Customize signature appearance, insert an image as signature displaying
            PageContentBuilder signatureAppearance = new PageContentBuilder(widget.Content.NormalContentSource);            
            using (Stream imgStream = File.OpenRead("sample.jpg"))
            {
                signatureAppearance.DrawImage(imgStream);
            }

            //Add this signature to first PDF page
            document.Pages[0].Annotations.Add(widget);
            document.AcroForm.FormFields.Add(signatureField);

            //Digital sign feature need the stream support reading, so you have to use ReadWrite mode here
            using (FileStream fs = new FileStream("signed.pdf", FileMode.Create, FileAccess.ReadWrite))
            {
                pdfFile.Export(document, fs);
            }

        }

        public static void ValidateSignature()
        {
            PdfFile pdfFile = new PdfFile();
            PdfDocument document = pdfFile.Import(File.ReadAllBytes("signed.pdf"));

            string status;

            //Handle first signature for example
            SignatureField signatureField = document.AcroForm.FormFields
                .Where(f => f.FieldType == FormFieldType.Signature).FirstOrDefault() as SignatureField;

            if (signatureField != null && signatureField.Signature != null)
            {               
                SignatureValidationResult validationResult;

                if (signatureField.Signature.TryValidate(out validationResult))
                {
                    if (validationResult.IsDocumentModified)
                    {
                        status = "Invalid";
                    }
                    else
                    {
                        if (validationResult.IsCertificateValid)
                        {
                            status = "Valid";
                        }
                        else
                        {
                            status = "Unknown";
                        }                       
                    }
                }
                else
                {
                    status = "Invalid";
                }
            }
           
        }

       

       

    }
}
