using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using presence.data.LocalData;
using presence.data.LocalData.Entity;
using presence.data.RemoteData.RemoteDataBase;
using presence.data.RemoteData.RemoteDataBase.DAO;

namespace presence.data.Repository
{
    public class SQLPresenceRepositoryImpl: IPresenceRepository
    {
        private readonly RemoteDataBaseContext _remoteDatabaseContext;

        public SQLPresenceRepositoryImpl(RemoteDataBaseContext remoteDatabaseContext)
        {
            _remoteDatabaseContext = remoteDatabaseContext;
        }

        public bool AddPresence(PresenceDao presence)
        {
           var presenceDao = new PresenceDao
            {
                Date = presence.Date,
                ClassNumber = presence.ClassNumber,
                UserId = presence.UserId,
                User = presence.User
            };
            _remoteDatabaseContext.Presences.Add(presenceDao);
            _remoteDatabaseContext.SaveChanges();
            return true;
        }

        public List<PresenceDao> GetPresenceByGroup(int groupId)
        {
            var listPresences = _remoteDatabaseContext.Presences
            .Where(x => x.GroupId == groupId).ToList();
            return listPresences;
        }

        public List<PresenceDao> GetPresenceByGroupAndDate(int groupId, DateOnly date)
        {
            var listPresences = _remoteDatabaseContext.Presences
            .Where(x => x.GroupId == groupId && x.Date == date).ToList();
            return listPresences;
        }

        public bool UncheckAttendence(int firstClass, int lastClass, DateOnly date, int userId)
        {
            var presToUpdate = _remoteDatabaseContext.Presences
                .Where(x => x.UserId == userId && x.ClassNumber >= firstClass 
                        && x.ClassNumber <= lastClass && x.Date == date).ToList();

            foreach (var pres in presToUpdate) {
                pres.IsAttendence = false;
            }
            _remoteDatabaseContext.SaveChanges();
            return true;
        }
    }
}