using InABox.WPF;
using InABox.Wpf;
using Syncfusion.UI.Xaml.ImageEditor;
using Syncfusion.UI.Xaml.ImageEditor.Enums;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Color = System.Windows.Media.Color;
using Image = System.Windows.Controls.Image;

namespace InABox.DynamicGrid
{
    /// <summary>
    /// Interaction logic for SignaturePadWindow.xaml
    /// </summary>
    public partial class SignaturePadWindow : ThemableWindow
    {
        public SignaturePadWindow(ImageSource? source, bool hasName = false)
        {
            InitializeComponent();

            if (!hasName)
            {
                NameContainer.Visibility = Visibility.Collapsed;
            }

            if(source != null)
            {
                Editor.Children.Add(new Image
                {
                    Source = source
                });
            }
            IsEmpty = source == null;
        }

        private bool IsEmpty;
        public BitmapSource? Image { get; private set; }
        public string SignatureName => NameEditor.Text;

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if (IsEmpty)
            {
                Image = null;
            }
            else
            {
                var rtb = new RenderTargetBitmap(400, 400, 96, 96, PixelFormats.Default);
                rtb.Render(Editor);

                using (var ms = new MemoryStream())
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(rtb));
                    encoder.Save(ms);

                    Image = ImageUtils.BitmapImageFromStream(ms);
                }
            }
            DialogResult = true;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void Clear_Click(object sender, RoutedEventArgs e)
        {
            Editor.Strokes.Clear();
            Editor.Children.Clear();
            IsEmpty = true;
        }

        private void Editor_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e)
        {
            IsEmpty = false;
        }
    }
}
