using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using SharedStorage;
using StackExchange.Redis;

namespace SampleApp.Controllers
{
    public class RedisController : Controller
    {
        // GET: Redis
        private ConnectionMultiplexer _multiplexer;
        private IDatabase _database;
        private CloudStorageAccount _storageAccount;
        private CloudTableClient _tableClient;
        private CloudTable _table;

        public RedisController()
        {
            _multiplexer = ConnectionMultiplexer.Connect(SharedStorage.StorageConst.RedisConnectionString);
            _database = _multiplexer.GetDatabase();
            _storageAccount = CloudStorageAccount.Parse(SharedStorage.StorageConst.StorageConnectionString);
            _tableClient = _storageAccount.CreateCloudTableClient();
            _table = _tableClient.GetTableReference(SharedStorage.StorageConst.TableName);
        }
        public ActionResult Index()
        {
            var members = _database.SetMembers(StorageConst.RedisSet).OrderBy(property=>property.ToString()[0]);
            return View(members);
        }

        public ActionResult Details(String id)
        {
            var hashSet = _database.HashGetAll(id);
            return View(hashSet);
        }

        public ActionResult WithRedis(String id)
        {

            var hashValue = _database.HashGet(id[0].ToString(),id);
            TableQuery<Model> query =
                new TableQuery<Model>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal,
                    hashValue.ToString()));
            DateTime time = DateTime.Now;
            
            var queryResult = _table.ExecuteQuery(query);
            ViewBag.TimeElapsed = (DateTime.Now - time).Milliseconds;
            return View(queryResult);
        }

        public ActionResult WithoutRedis(String id)
        {
            var split = id.Split(' ');
           
            TableQuery<Model> query =
                new TableQuery<Model>().Where(TableQuery
                .CombineFilters
                (
                    TableQuery.GenerateFilterCondition("FirstName",QueryComparisons.Equal,split[0]),
                    TableOperators.And,
                    TableQuery.GenerateFilterCondition("LastName",QueryComparisons.Equal,split[1])
                ));
            Stopwatch watch = Stopwatch.StartNew();
            watch.Start();
            var queryResult = _table.ExecuteQuery(query);
            watch.Stop();
            ViewBag.TimeElapsed = watch.ElapsedMilliseconds;
            return View(queryResult);
        }
    }
}