using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Infrastructure;
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 SQLUserRepositoryImpl: IUserRepository
    {
        private readonly RemoteDataBaseContext _remoteDatabaseContext;
        public SQLUserRepositoryImpl(RemoteDataBaseContext remoteDatabaseContext)
        {
            _remoteDatabaseContext = remoteDatabaseContext;
        }

        public List<UserDao> GetAllUser()
        {
            return _remoteDatabaseContext.Users.Select(u => new UserDao 
            {
                FIO = u.FIO,
                UserId = u.UserId,
                GroupId = u.GroupId
            }).ToList();
        }


        public bool RemoveUserById(int userId)
        {
            var userLocal = _remoteDatabaseContext.Users
                .Where(x => x.UserId== userId).FirstOrDefault();
            if (userLocal == null) return false;

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

        public UserDao GetUserById (int userId) {
            var userLocal = _remoteDatabaseContext.Users
                    .Where(x => x.UserId == userId).FirstOrDefault();
            if (userLocal == null) return null;

            return userLocal;
        }

        public bool UpdateUser(UserDao userUpdate) {
            var userLocal = _remoteDatabaseContext.Users
                    .Where(x => x.UserId == userUpdate.UserId).FirstOrDefault();
            if (userLocal == null) return false;
            userLocal.FIO = userUpdate.FIO;
            userLocal.GroupId = userUpdate.GroupId;
            _remoteDatabaseContext.SaveChanges();
            return true;

        }

        public bool UpdateUserById(int userId, string fio, int groupId) {
            var userLocal = _remoteDatabaseContext.Users
                    .Where(x => x.UserId == userId).FirstOrDefault();
            if (userLocal == null) return false;

            userLocal.FIO = fio;
            userLocal.GroupId = groupId;
            _remoteDatabaseContext.SaveChanges();

            return true;
        }
    }
}