using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using presence.data.RemoteData;
using presence.data.RemoteData.RemoteDataBase;
using presence.data.RemoteData.RemoteDataBase.DAO;
using presence.data.Repository;

namespace data.Repository
{
    public class AdminRepositoryImp: IAdminRepository
    {
        private readonly RemoteDataBaseContext _remoteDataBaseContext;

        public AdminRepositoryImp(RemoteDataBaseContext remoteDataBaseContext)
        {
            _remoteDataBaseContext = remoteDataBaseContext;
        }

        public bool AddStudents(GroupDao group, List<string> students)
        {
            _remoteDataBaseContext.Groups.Add(group);
            _remoteDataBaseContext.SaveChanges();
            foreach (string student in students)
            {
                var user = new UserDao
                {
                    FIO = student,
                    GroupId = group.Id,
                    Group = _remoteDataBaseContext.Groups.Where(x => x.Id == group.Id).FirstOrDefault(),
                };
                _remoteDataBaseContext.Users.Add(user);
            }
            _remoteDataBaseContext.SaveChanges();
            return true;
        }

        public IEnumerable<GroupDao> GetAllGroupsWithStudents()
        {
            return _remoteDataBaseContext.Groups.Select(x => new GroupDao 
                { 
                    Id = x.Id, 
                    Name = x.Name, 
                    User = _remoteDataBaseContext.Users.Where(it => it.GroupId == x.Id).ToList()}).ToList();
        }

        public UserDao GetStudentInfo(int userId)
        {
            return _remoteDataBaseContext.Users.Where(x => x.UserId == userId).FirstOrDefault();
        }

        public bool RemoveUserById(int userId, int groupId)
        {
            var userLocal = _remoteDataBaseContext.Users
                .Where(x => x.UserId== userId && x.GroupId == groupId).FirstOrDefault();
            if (userLocal == null) return false;

            _remoteDataBaseContext.Users.Remove(userLocal);
            _remoteDataBaseContext.SaveChanges();
            return true;
        }
    }
}