﻿using Ojibwe.Public.Sdk;
using Ojibwe.Public.Sdk.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
using Ojibwe.Public.Sdk.Utilities;

namespace Ojibwe.Tools.StressTest
{
    class Program
    {
        private static MD5 md5 = MD5.Create();

        static void Main(string[] args)
        {
            XmlConfigurator.Configure();
            if (args.Length < 1)
                throw new ApplicationException("Please specify Ojibwe endpoint.");

            string address = args[0];

            OjibweClient client = new OjibweClient(address);

            string username = string.Format("StressTest{0}", DateTime.Now.Ticks.ToString());
            Stream privateKey = null;
            var currentUser = client.Register(username, "Password01", out privateKey);
            
            for (int i = 0; i < 10; i++)
            {
                Container container = new Container();
                container.Name = string.Format("Container_{0}", i);
                currentUser.Containers.Add(container);
            }

            Random random = new Random();

            foreach (var container in currentUser.Containers.Items)
            {
                byte[] randomBytes = new byte[64];
                for (int i = 0; i < 100; i++)
                {
                    try
                    {
                        random.NextBytes(randomBytes);

                        Guid checksum = Guid.Empty;
                        lock (md5)
                            checksum = new Guid(md5.ComputeHash(randomBytes));
                        MemoryStream ms = new MemoryStream(randomBytes);

                        var sdkBlob = container.StoreBlob(ms, currentUser.PublicKey,
                            new KeyValuePair<string, string>("DateTime.Ticks", DateTime.Now.Ticks.ToString()),
                            new KeyValuePair<string, string>("CheckSum", checksum.ToString()));
                        Console.WriteLine("Stored BlobId: {0}", sdkBlob.Id);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to store blob.");
                    }
                }
            }
            Parallel.ForEach(currentUser.Containers.Items, new ParallelOptions() { MaxDegreeOfParallelism = 8 },
                (container) =>
                {
                    foreach (var blob in container.Blobs.Items)
                    {
                        Console.WriteLine("BlobID: {0}", blob.Id);
                        string checkSum = null;
                        if (!blob.Info.TryGetValue("CheckSum", out checkSum))
                        {
                            Console.WriteLine("Could not find checksum.");
                            continue;
                        }

                        Guid g = Guid.Parse(checkSum);
                        var bytes = StreamUtility.GetBytes(currentUser.DecryptBlob(blob, privateKey));
                            
                        if(!VerifyCheckSum(g, bytes))
                            Console.WriteLine("CheckSums did not match for BlobId: {0}", blob.Id);
                    }
                });
        }
        
        private static bool VerifyCheckSum(Guid purportedCheckSum, byte[] data)
        {
            var checkSum = new Guid(md5.ComputeHash(data));
            Console.WriteLine("Expected: {0} -- Actual: {1}", purportedCheckSum, checkSum);
            return checkSum.Equals(purportedCheckSum);
        }
    }
}
