using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation.Diagnostics;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace PhotoFilter
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class ImagePage : Page
    {
        public ImagePage()
        {
            this.InitializeComponent();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
			ImageDescriptor descriptor = (e.Parameter as ImageItem).GetDescriptor();
			var image = await ImageItem.FromDescriptor(descriptor);
            await image.FetchPicture();
            imgSelectedImage.Source = await image.GetPictureAsync();
            this.DataContext = image;
            Window.Current.SizeChanged += WindowSizeChanged;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
			//Uncomment to free the page
			//Window.Current.SizeChanged -= WindowSizeChanged;
        }

        private void WindowSizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
        {
            Debug.WriteLine("Window size changed (somehow)!");
        }

        async private void btnLocal_Click(object sender, RoutedEventArgs e)
        {
            var nativeObject = new PhotoFilterLib.ImageFilter();
            WriteableBitmap bitmap = (WriteableBitmap)imgSelectedImage.Source;
            IBuffer pixelBuffer = bitmap.PixelBuffer;
            var rawPixelArray = new byte[bitmap.PixelHeight * bitmap.PixelWidth * 4];
            Stream tempStream = bitmap.PixelBuffer.AsStream();
            tempStream.Read(rawPixelArray, 0, rawPixelArray.Length);
            rawPixelArray = nativeObject.AntiqueImage(rawPixelArray);
            await updateImage(bitmap, rawPixelArray);
			App.channel.LogMessage("Applied Filter", LoggingLevel.Information);
        }

        async private Task updateImage(WriteableBitmap bitmap, byte[] newPixels)
        {
            using (Stream stream = bitmap.PixelBuffer.AsStream())
            {
                await stream.WriteAsync(newPixels, 0, newPixels.Length);
            }

            bitmap.Invalidate();
        }
    }
}
