using FSI.BT.IR.Plc.Settings.Log.Data;
using FSI.BT.IR.Plc.Settings.Log.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;

namespace FSI.BT.IR.Plc.Settings.Log.Controllers
{
    public class HomeController : Controller
    {        
        private readonly ApplicationDbContext _context;
        private readonly DataManager _dataManager;

        public HomeController(ApplicationDbContext context)
        {
            
            _context = context;
            _dataManager = new(context);
        }

        public async Task<IActionResult> IndexAsync()
        {
            Task<List<Logging>> loggData = _dataManager.LoadLggingsAsync();

            // Daten nach Parameter Id gruppieren
            var groupedDatas = (await loggData).GroupBy(x => x.ParameterId);

            List<Models.Statistics> statistics = new();

            // Detail-Statistik erstellen
            foreach (var groupedData in groupedDatas)
            {
                var tmp = groupedData.GroupBy(x => x.Timestamp.Hour);
                Statistics statistic = new();
                statistic.Parameter = groupedData.First().Parameter;
                statistic.Cnt = groupedData.Count();
                statistic.MinValue = groupedData.Min(x => Convert.ToDouble(x.Value));
                statistic.MaxValue = groupedData.Max(x => Convert.ToDouble(x.Value));

                statistics.Add(statistic);
            }

            
            
            //List<Parameter> tmps = await _dataManager.LoadParameterAsync();
            //int i = 1;
            //foreach (var tmp in tmps)
            //{
            //    tmp.Id = tmps.Max(x => x.Id + i);
            //    i++;
            //    _context.Parameters.Add(tmp);
            //}

            //_context.SaveChanges();




            return View(statistics);
        }
    }
}
