using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;

namespace PerfDiagHubXAML
{
	class ImageHelper
	{
		public static async Task<WriteableBitmap> Convert(string uri)
		{
			(App.Current as App).LogMessage("Start Convert");
			WebRequest wr =  WebRequest.Create(uri);
			WebResponse response = await wr.GetResponseAsync();
			InMemoryRandomAccessStream s = new InMemoryRandomAccessStream();
			response.GetResponseStream().CopyTo(s.AsStream());
			BitmapDecoder decoder = await BitmapDecoder.CreateAsync(s);
			PixelDataProvider pdp = await decoder.GetPixelDataAsync();
			byte[] pixels = pdp.DetachPixelData();
			for (int i = 0; i < pixels.Length; i += 4)
			{
				byte color = (byte)((pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3);
				pixels[i] = color;
				pixels[i + 1] = color;
				pixels[i + 2] = color;
			}

			WriteableBitmap wb = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);		
			Stream stream = wb.PixelBuffer.AsStream();
			await stream.WriteAsync(pixels, 0, pixels.Length);
			(App.Current as App).LogMessage("End Convert");
			return wb;
		}
	}
}
