using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;

namespace DbSpeed.Controllers
{
	public class AzureBlobController : Controller
	{
		private const string TestContainerName = "test";
		private readonly CloudBlobContainer _container;

		public AzureBlobController(IConfiguration configuration)
		{
			var credentials = new StorageCredentials(configuration["AzureAccountName"], configuration["AzureKeyValue"]);
			var azureBlobUri = new Uri("https://" + configuration["AzureAccountName"] + ".blob.core.windows.net");
			var client = new CloudBlobClient(azureBlobUri, credentials);
			_container = client.GetContainerReference(TestContainerName);
		}

        [HttpGet]
		public async Task<IEnumerable<string>> Get()
		{
			var result = new List<string>();
			var watch = new Stopwatch();

			for (int i = 1; i < 11; i++)
			{
				watch.Restart();
				CloudPageBlob blob = _container.GetPageBlobReference("test1.txt");
				using (var stream = await blob.OpenReadAsync())
				{
					stream.ReadByte();
				}
				watch.Stop();
				result.Add($"Azure Blob {i} try: {watch.ElapsedMilliseconds}");
			}
			return result;
		}

        [HttpPost]
		public async Task<IEnumerable<string>> Post()
		{
			var result = new List<string>();
			var watch = new Stopwatch();
			var buffer = new byte[512];
			System.Text.Encoding.UTF8.GetBytes("Testcontent1").CopyTo(buffer, 0);
			await _container.CreateIfNotExistsAsync();

			for (int i = 1; i < 11; i++)
			{
				watch.Restart();
				CloudPageBlob blob = _container.GetPageBlobReference(string.Format("test{0}.txt", i));
				using (var stream = await blob.OpenWriteAsync(buffer.Length))
				{
					await stream.WriteAsync(buffer, 0, buffer.Length);
				}
				watch.Stop();
				result.Add($"Azure Blob {i} try: {watch.ElapsedMilliseconds}");
			}
			return result;
		}

        [HttpDelete]
		public async Task<IActionResult> Delete()
		{
			await _container.DeleteIfExistsAsync();
			return Ok();
		}
	}
}