using Demo.Domain.Models;
using Demo.Data.LocalData;
using Demo.Data.RemoteData.RemoteDataBase;
using Demo.Data.RemoteData.RemoteDataBase.DAO;

namespace Demo.Data.Repository
{
    public class SQLGroupRepositoryImpl : IGroupRepository
    {
        private readonly RemoteDatabaseContext _remoteDatabaseContext;

        public SQLGroupRepositoryImpl(RemoteDatabaseContext remoteDatabaseContext){
            _remoteDatabaseContext = remoteDatabaseContext;
            GetAllGroups = _remoteDatabaseContext.Groups.Select(x => new GroupLocalEntity{Name = x.Name, ID = x.ID}).ToList();
        }

        public List<GroupLocalEntity> GetAllGroups
        { get; set; }

        public List<GroupLocalEntity> GetAllGroup()
        {
            return _remoteDatabaseContext.Groups.Select(x => new GroupLocalEntity{Name = x.Name, ID = x.ID}).ToList();
        }

        public GroupLocalEntity? GetGroupById(int ID){
            var groupDAO = _remoteDatabaseContext.Groups.FirstOrDefault(x => x.ID == ID);
            return new GroupLocalEntity{Name = groupDAO.Name, ID = groupDAO.ID};
        }

        public GroupLocalEntity? CreateGroup(string Name) {
            GroupDAO groupDAO = new GroupDAO{Name = Name};
            var result = _remoteDatabaseContext.Groups.Add(groupDAO);
            _remoteDatabaseContext.SaveChanges();
            return new GroupLocalEntity{Name = groupDAO.Name, ID = groupDAO.ID};
        }

        public GroupLocalEntity? UpdateGroup(GroupLocalEntity updatedGroup){
            var group = _remoteDatabaseContext.Groups.FirstOrDefault(x => x.ID == updatedGroup.ID);
            if (group == null){
                return null;
            }

            group.Name = updatedGroup.Name;
            _remoteDatabaseContext.SaveChanges();
            return new GroupLocalEntity{Name = group.Name, ID = group.ID};
        }

        public bool RemoveGroupByID(int ID){
            var groupDAO = _remoteDatabaseContext.Groups.FirstOrDefault(x => x.ID == ID);
            _remoteDatabaseContext.Groups.Remove(groupDAO);
            _remoteDatabaseContext.SaveChanges();
            return true;
        }
    }
}