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;

namespace ResourcesManager.Controllers
{
    public class StatisticsController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        public ActionResult Index(StatisticType? statTypeId, int? resId)
        {
            if (statTypeId == null)
            {
                statTypeId = Models.StatisticType.Reserv;
            }
            if (resId == null)
            {
                resId = db.Resources.FirstOrDefault().Id;
            }
            var model = new StatisticViewModel();
            var today = DateTime.Today.AddDays(-30.0);
            model.ByType = db.Statistic.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 = db.Statistic.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 = db.Statistic.GroupBy(l => l.StatisticType).Select(j => new ByTypeCircle() { Name = ((StatisticType)j.Key).ToString(), Value = j.Count() }).ToList();
            var subscibedUser = db.Resources.Select(k => k.Users.Count()).Sum();
            var allUsers = db.Users.Count() * db.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(db.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)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
