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

namespace Posechaemost.Data.Repository
{
    public class SQLGroupRepositoryImpl : IGroupRepository
    {
        private readonly RemoteDataBaseContext _remoteDatabaseContext;

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

        public bool AddGroup(GroupDao group)
        {
            var groupDao = new GroupDao
            {
                Name = group.Name
            };
            _remoteDatabaseContext.Groups.Add(groupDao);
            _remoteDatabaseContext.SaveChanges();
            return true;
        }

        public List<GroupDao> GetAllGroup()
        {
            return _remoteDatabaseContext.Groups
                .Include(g => g.User)
                .Select(g => new GroupDao
                {
                    Name = g.Name,
                    Id = g.Id,
                    User = g.User.Select(u => new UserDao
                    {
                        UserId = u.UserId,
                        FIO = u.FIO,
                        GroupId = u.GroupId,
                    }).ToList()
                }).ToList();
        }

        public GroupDao GetGroupById(int groupID)
        {
            var groupLocal = _remoteDatabaseContext.Groups
                                .Where(g => g.Id == groupID).FirstOrDefault();
            if (groupLocal == null) return null;
            return groupLocal;
        }

        public bool RemoveGroupById(int groupID)
        {
            var groupLocal = _remoteDatabaseContext.Groups
                .Where(x => x.Id == groupID).FirstOrDefault();
            if (groupLocal == null) return false;

            _remoteDatabaseContext.Groups.Remove(groupLocal);
            _remoteDatabaseContext.SaveChanges();
            return true;
        }

        public bool UpdateGroupById(int groupID, string name)
        {
            var groupLocal = _remoteDatabaseContext.Groups
                .Include(g => g.User)
              .Where(x => x.Id == groupID).FirstOrDefault();
            if (groupLocal == null) return false;
            
            groupLocal.Name = name;

            groupLocal.User = _remoteDatabaseContext.Users
                .Where(x => x.GroupId == groupLocal.Id)
                .Select(user => new UserDao
                {
                    UserId = user.UserId,
                    FIO = user.FIO,
                    GroupId = user.GroupId
                }).ToList();


            _remoteDatabaseContext.SaveChanges();
            return true;
        }
    }
}