// <copyright file="Default.aspx.cs" company="Scriptel Corporation">
//      Copyright 2014 - Scriptel Corporation
// </copyright>
namespace ASPNetExample
{
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Web.UI;
    using EasyScriptAPI;

    /// <summary>
    ///     This class implements a very simple examples of an ASP.NET signature handler.
    /// </summary>
    public partial class Default : Page
    {
        /// <summary>
        /// This event fires when the submit button is pressed.
        /// </summary>
        /// <param name="sender">Object sending the event.</param>
        /// <param name="e">Arguments to the event.</param>
        protected void SubmitButtonClick(object sender, EventArgs e)
        {
            EasyScript keyboard = new EasyScript();
            char sigStart = keyboard.GetSignatureProtocol().GetStartStream();
            char cardStart = keyboard.GetCardProtocol().GetStartStream();
            try
            {
                if (Signature.Text.Length > 0 && Signature.Text[0] == sigStart)
                {
                    Signature s = keyboard.ParseSignature(Signature.Text);
                    Results.Text = s.ToString();
                    using (MemoryStream stream = new MemoryStream())
                    {
                        // Render the image in memory.
                        System.Drawing.Image i = keyboard.RenderSignature(s, Color.Black, Color.White, 2, 2);

                        // Save the image as a PNG in memory.
                        i.Save(stream, ImageFormat.Png);

                        // Output the result as a data url encoded image.
                        SignatureImage.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray());
                    }
                }
                else if (Signature.Text.Length > 0 && Signature.Text[0] == cardStart)
                {
                    // Parse the card swipe, watch out because browsers switch \r for \n.
                    CardSwipe c = keyboard.ParseCardSwipe(Signature.Text.Replace("\n", "\r"));

                    // There is no image for cards.
                    SignatureImage.ImageUrl = string.Empty;
                    Results.Text = c.ToString();
                }
                else
                {
                    Results.Text = "Unable to identify any keyboard output.";
                }
            }
            catch (Exception ex)
            {
                Results.Text = "An exception occurred while processing: \n" + ex.ToString();
            }
        }
    }
}