using Demo.Data.LocalData;
using Demo.Data.RemoteData.RemoteDataBase;
using Demo.Data.RemoteData.RemoteDataBase.DAO;
using Demo.domain.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Demo.Data.Repository
{
    public class SQLPresenceRepositoryImpl : IPresenceRepository
    {
        private readonly RemoteDatabaseContext _remoteDatabaseContext;

        public SQLPresenceRepositoryImpl(RemoteDatabaseContext remoteDatabaseContext)
        {
            _remoteDatabaseContext = remoteDatabaseContext;
        }
        public List<PresenceDao> GetPresenceForAbsent(DateTime date, int GroupId)
        {
            return _remoteDatabaseContext.PresenceDaos.Where(p => p.GroupId == GroupId && p.Date==DateOnly.FromDateTime(date)).ToList();
        }
        public List<PresenceDao> GetPresenceByDateAndGroup(DateTime date, int groupId)
        {
            return _remoteDatabaseContext.PresenceDaos.Where(p => p.Date == DateOnly.FromDateTime(date) &&
                                         _remoteDatabaseContext.Users.Any(u => u.GroupId == groupId && u.UserId == p.UserId)).ToList();
        }

        // Реализация метода для получения всех данных по группе
        public List<PresenceDao> GetPresenceByGroup(int groupId)
        {
            return _remoteDatabaseContext.PresenceDaos.Where(p => p.GroupId == groupId).ToList();
        }

        public void SavePresence(List<PresenceDao> presences)
        {
            _remoteDatabaseContext.PresenceDaos.AddRange(presences.Select(it => new PresenceDao
            {
                Date = it.Date,
                IsAttedance = it.IsAttedance,
                LessonNumber = it.LessonNumber,
                UserId = it.UserId,
                GroupId = it.GroupId
            }));
            _remoteDatabaseContext.SaveChanges();
        }

        public DateOnly? GetLastDateByGroupId(int groupId)
        {
            // Проверяем наличие записей о посещаемости в базе данных для данной группы.
            var lastDate = _remoteDatabaseContext.PresenceDaos
                .Where(p => p.GroupId == groupId)
                .OrderByDescending(p => p.Date)
                .Select(p => p.Date)
                .FirstOrDefault();

            return lastDate == default ? (DateOnly?)null : lastDate;
        }

    }
}
