using EVCB_OCPP.Domain;
using EVCB_OCPP.Packet.Messages.SubTypes;
using EVCB_OCPP.WSServer.Dto;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace EVCB_OCPP.WSServer.Service
{

    public interface IBusinessService
    {
        Task<IdTokenInfo> Authorize(string chargeBoxId, string idTag);

        Task NotifyFaultStatus(ErrorDetails details);

        Task NotifyConnectorUnplugged(string chargeBoxId,string data);

    }

    public class BusinessServiceFactory
    {
        public BusinessServiceFactory(IServiceProvider serviceProvider, IDbContextFactory<MainDBContext> mainDBContextFactory)
        {
            this.serviceProvider = serviceProvider;
            this.mainDBContextFactory = mainDBContextFactory;
        }

        private readonly IServiceProvider serviceProvider;
        private readonly IDbContextFactory<MainDBContext> mainDBContextFactory;

        public async Task<IBusinessService> CreateBusinessService(string customerId)
        {
            bool isCallOut = false;
            using (var db = this.mainDBContextFactory.CreateDbContext())
            {
                isCallOut = await db.Customer.Where(x => x.Id == new Guid(customerId)).Select(x => x.CallPartnerApiOnSchedule).FirstOrDefaultAsync();
            }

            //return isCallOut ? new OuterBusinessService(customerId) : new LocalBusinessService(customerId);
            if(isCallOut)
            {
                OuterBusinessService outerBusinessService = serviceProvider.GetService<OuterBusinessService>();
                outerBusinessService.CustomerId = customerId;
                return outerBusinessService;
            }
            LocalBusinessService toReturn = serviceProvider.GetService<LocalBusinessService>();
            toReturn.CustomerId = customerId;
            return toReturn;

            //return isCallOut ? new OuterBusinessService(customerId) : 
        }

    }
}
