using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;

namespace WPFManipulation
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();
			GetImages();
		}

		private void canvas_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
		{
			touchStatus.Text = "Manipulation starting";
			e.ManipulationContainer = canvas;
		}

		private void canvas_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
		{
			touchStatus.Text = "Manipulation delta";
			FrameworkElement element = e.Source as FrameworkElement;

			if(element == null)
				return;

			Matrix matrix = ((MatrixTransform)element.RenderTransform).Matrix;

			Point center = new Point(element.ActualWidth/2, element.ActualHeight/2);
			center = matrix.Transform(center);

			matrix.ScaleAt(e.DeltaManipulation.Scale.X, e.DeltaManipulation.Scale.Y, center.X, center.Y);

			matrix.RotateAt(e.DeltaManipulation.Rotation, center.X, center.Y);

			matrix.Translate(e.DeltaManipulation.Translation.X, e.DeltaManipulation.Translation.Y);
			((MatrixTransform)element.RenderTransform).Matrix = matrix;

			e.Handled = true;
		}

		private void canvas_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
		{
			touchStatus.Text = "Manipulation completed";
		}

		private void GetImages()
		{
			string[] files = Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg");
			foreach(string file in files)
			{
				BitmapImage bi = new BitmapImage(new Uri(file));
				Image image = new Image();
				image.IsManipulationEnabled = true;
				image.Source = bi;
				image.Width = 512;
				image.Height = 512;
				// by default this is Matrix.Identity which is a constant.  Must create a new MatrixTransform
				// so it can be set/edited by the touch stuff
				image.RenderTransform = new MatrixTransform();
				canvas.Children.Add(image);
			}
		}
	}
}
