using DAL.Models.Entities;
using DAL.Models.Filters;
using HRD.LDAPService;
using HRD.WebApi.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DAL.Repositories
{
    public class WebAppToDepartmentRepository : BaseRepository<WebAppToDepartment>
    {
        private readonly LdapManager _ldapManager;

        public WebAppToDepartmentRepository(WebApiContext context, LdapManager ldapManager) : base(context)
        {
            _ldapManager = ldapManager;
        }

        public async Task<List<WebAppToDepartment>> GetListByFilterAsync(EmployeeToWebAppFilter filter, bool asNoTracking = true)
        {
            var items = this.RepositoryContext.Set<WebAppToDepartment>().AsQueryable();

            if (filter.EmployeeToWebAppId != null && filter.EmployeeToWebAppId != 0)
            {
                items = items.Where(x => x.EmployeeToWebAppId == filter.EmployeeToWebAppId);
            }

            return asNoTracking ? await items.AsNoTracking().ToListAsync() : await items.ToListAsync();
        }

        private async Task<bool> AddUserToAdGroup(WebAppToDepartment entity)
        {
            return await ProcessGroup(entity, "adding");
        }

        private async Task<bool> RemoveUserFromAdGroup(WebAppToDepartment entity)
        {
            return await ProcessGroup(entity, "deleting");
        }

        private async Task<bool> ProcessGroup(WebAppToDepartment entity, string action)
        {
            if (entity == default) throw new ArgumentNullException(nameof(entity));

            var employee2Web = await GetEmployeeToWebAppById(entity.EmployeeToWebAppId);
            if (employee2Web == default) throw new ArgumentNullException(nameof(employee2Web));

            var department = await GetDepartmentById(entity.DepartmentId);
            if (department == default) throw new ArgumentNullException(nameof(department));
            if (string.IsNullOrEmpty(department.AdGroupDepartmentName)) return true;

            var employee = await GetEmployeeById(employee2Web.EmployeeId);
            if (employee == default) throw new ArgumentNullException(nameof(employee));

            var webapp = await GetWebAppById(employee2Web.WebAppId);
            if (webapp == default) throw new ArgumentNullException(nameof(webapp));

            bool result;
            var isAdding = action == "adding";

            var groupSuffix = $"{webapp.AdWebAppName}_{department.AdGroupDepartmentName}";
            if (!_ldapManager.IsWindreamSuffixGroup(groupSuffix)) return true;
            try
            {
                if (isAdding) result = _ldapManager.AD_AddUserloginToGroup(employee.LoginName, groupSuffix);
                else result = _ldapManager.AD_RemoveUserFromGroup(employee.LoginName, groupSuffix);
            }
            catch (Exception ex)
            {
                WriteLogException(ex, $"An error occurred while '{action}' the '{employee.LoginName}' into '{groupSuffix}'.");
                return false;
            }

            if (!result)
            {
                WriteLogError($"An error occurred while '{action}' the '{employee.LoginName}' into '{groupSuffix}'.");
                return false;
            };
            return true;
        }

        public override async Task<bool> AddAsync(WebAppToDepartment entity, bool saveEntity = true)
        {
            if (await AddUserToAdGroup(entity))
            {
                var result = await base.AddAsync(entity, saveEntity);
                return result;
            }
            return false;
        }

        public override async Task<bool> AddListAsync(List<WebAppToDepartment> entities, bool saveEntity = true)
        {
            var result = true;
            for (int i = 0; i < entities.Count; i++)
            {
                if (!await AddAsync(entities[i], saveEntity)) result = false;
            }
            return result;
        }

        public override async Task<bool> DeleteByIdAsync(int id, bool saveEntity = true)
        {
            try
            {
                var entity = await base.GetByIdAsync(id);
                if (entity == default)
                {
                    throw new ArgumentNullException(nameof(entity));
                }

                if (await RemoveUserFromAdGroup(entity))
                {
                    var result = await base.DeleteByIdAsync(id, saveEntity);
                    return result;
                }
                return false;
            }
            catch (Exception ex)
            {
                WriteLogException(ex, $"An error occurred while deleting the Id {id}");
                return false;
            }
        }

        public async Task<EmployeeToWebApp> GetEmployeeToWebAppById(int entityId)
        {
            try
            {
                return await this.RepositoryContext.Set<EmployeeToWebApp>().FindAsync(entityId);
            }
            catch (Exception ex)
            {
                WriteLogException(ex, $"{typeof(EmployeeToWebApp).Name} id:{entityId}");
            }
            return default;
        }

        public async Task<WebApp> GetWebAppById(int entityId)
        {
            try
            {
                return await this.RepositoryContext.Set<WebApp>().FindAsync(entityId);
            }
            catch (Exception ex)
            {
                WriteLogException(ex, $"{typeof(WebApp).Name} id:{entityId}");
            }
            return default;
        }

        public async Task<Department> GetDepartmentById(int entityId)
        {
            try
            {
                return await this.RepositoryContext.Set<Department>().FindAsync(entityId);
            }
            catch (Exception ex)
            {
                WriteLogException(ex, $"{typeof(Department).Name} id:{entityId}");
            }
            return default;
        }

        public async Task<Employee> GetEmployeeById(int entityId)
        {
            try
            {
                return await this.RepositoryContext.Set<Employee>().FindAsync(entityId);
            }
            catch (Exception ex)
            {
                WriteLogException(ex, $"{typeof(Employee).Name} id:{entityId}");
            }
            return default;
        }
    }
}