using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.DAL.Context;
using PARR.DAL.Models;
using PARR.DAL.Services.Abstracts;
using PARR.DAL.Services.Interfaces;

namespace PARR.DAL.Services.Implementations
{
    internal class HostService : BaseService<Host>, IHostService
    {
        private readonly DataContext dataContext;
        private readonly ILogger<HostService> logger;

        protected override DbSet<Host> EntitySet => dataContext.Hosts;

        protected override DataContext EntitiContext => dataContext;
        public HostService(DataContext dataContext, ILogger<HostService> logger) : base(logger)
        {
            this.dataContext = dataContext;
            this.logger = logger;
        }


        public async Task<Host?> GetHostWithAppsByIpAsync(string ip)
        {
            return await GetHostWithIncludeApps()
                .AsSplitQuery()
                .FirstOrDefaultAsync(h => h.IP == ip);
        }


        public async Task<Host?> GetHostWithAppsByEkAsync(string ek)
        {
            return await GetHostWithIncludeApps()
                .AsSplitQuery()
                .FirstOrDefaultAsync(h => h.Ek.ToLower() == ek.ToLower());
        }


        private IQueryable<Host> GetHostWithIncludeApps()
        {
            return EntitySet
                .Include(t => t.ApplicationsInHosts)
                    .ThenInclude(a => a.Application)
                    .ThenInclude(t => t!.ApplicationType)
                .Include(t => t.WorkGroup);
        }


        public async Task<Host?> GetByIpAsync(string ip)
        {
            return await EntitySet.FirstOrDefaultAsync(t => t.IP == ip);
        }


        public async Task<Host?> GetByEkAsync(string ek)
        {
            return await EntitySet.FirstOrDefaultAsync(t => t.Ek.ToLower() == ek.ToLower());
        }


    }
}
