using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ResourcesManager.Models;
using ResourcesManager.ViewModels;
using System.Data.Entity.Core.Objects;
using ResourcesManager.Interfaces;
using ResourcesManager.Repositories;

namespace ResourcesManager.Controllers
{
    public class StatisticsController : Controller
    {
        private ApplicationDbContext context;
        private IStatisticRepository statisticRepository;

        public StatisticsController()
        {
            context = new ApplicationDbContext();
            this.statisticRepository = new StatisticRepository(context);
        }

        public StatisticsController(IStatisticRepository statisticRepository)
        {
            this.statisticRepository = statisticRepository;
        }

        public ActionResult Index(StatisticType? statTypeId, int? resId)
        {
            if (statTypeId == null)
            {
                statTypeId = Models.StatisticType.Reserv;
            }
            if (resId == null)
            {
                resId = context.Resources.FirstOrDefault().Id;
            }
            var statistics = statisticRepository.GetStatistics();
            var model = new StatisticViewModel();
            var today = DateTime.Today.AddDays(-30.0);
            model.ByType = statistics.Where(k => k.StatisticType == statTypeId && k.DateTime > today).GroupBy(l => DbFunctions.TruncateTime(l.DateTime)).Select(j => new ByType() { Name = (DateTime)j.Key, Value = j.Count() }).ToList();
            model.ByResource = statistics.Where(k => k.ResourceId == resId & k.DateTime > today).GroupBy(l => DbFunctions.TruncateTime(l.DateTime)).Select(j => new ByResource() { Name = (DateTime)j.Key, Value = j.Count() }).ToList();
            model.ByTypeCircle = statistics.GroupBy(l => l.StatisticType).Select(j => new ByTypeCircle() { Name = ((StatisticType)j.Key).ToString(), Value = j.Count() }).ToList();
            var subscibedUser = context.Resources.Select(k => k.Users.Count()).Sum();
            var allUsers = context.Users.Count() * context.Resources.Count();
            model.Subscribe = new List<Subscribe>();
            model.Subscribe.Add(new Subscribe() { Name = "Subscribed user", Value = subscibedUser });
            model.Subscribe.Add(new Subscribe() { Name = "Unsubscibed user", Value = allUsers - subscibedUser });
            model.Resources = new SelectList(context.Resources, "Id", "Name", resId);
            model.StatisticType = new SelectList(Enum.GetValues(typeof(StatisticType)).Cast<StatisticType>(), (int)statTypeId);
            return View(model);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                context.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
