using JiShe.CollectBus.DataChannels;
using JiShe.CollectBus.Interceptors;
using JiShe.CollectBus.Protocol;
using JiShe.CollectBus.ScheduledMeterReading;
using JiShe.CollectBus.Workers;
using JiShe.ServicePro.FreeRedisProvider;
using JiShe.ServicePro.FreeSqlProvider;
using JiShe.ServicePro.IoTDBManagement;
using JiShe.ServicePro.IoTDBManagement.TableModels;
using JiShe.ServicePro.Kafka;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using System.Threading.Channels;
using Volo.Abp;
using Volo.Abp.Application;
using Volo.Abp.Autofac;
using Volo.Abp.AutoMapper;
using Volo.Abp.Modularity;

namespace JiShe.CollectBus;

[DependsOn(
    typeof(CollectBusDomainModule),
    typeof(CollectBusApplicationContractsModule),
    typeof(AbpDddApplicationModule),
    typeof(AbpAutoMapperModule),
    typeof(ServiceProFreeRedisProviderModule),
    typeof(ServiceProFreeSqlProviderModule),
    typeof(ServiceProKafkaModule),
    typeof(IoTDBManagementApplicationModule),
    typeof(AbpAutofacModule),
    typeof(CollectBusDomainSharedModule),
    typeof(CollectBusProtocolModule)
)]
public class CollectBusApplicationModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        var configuration = context.Services.GetConfiguration();

        context.Services.AddAutoMapperObjectMapper<CollectBusApplicationModule>();
        Configure<AbpAutoMapperOptions>(options => { options.AddMaps<CollectBusApplicationModule>(true); });

        context.Services.AddHostedService<ScheduledMeterReadingBackGroundWorkService>();

        //context.Services.AddSingleton(new MappingConfiguration()
        //    .Define(new CollectBusMapping()));

        // 注册拦截器
        context.Services.OnRegistered(ctx =>
        {
            var methods = ctx.ImplementationType.GetMethods();
            var any = methods.Any(a => a.GetCustomAttribute<LogInterceptAttribute>() != null);
            if (any) ctx.Interceptors.TryAdd<LogInterceptor>();
        });

    }

    public override async Task OnApplicationInitializationAsync(
        ApplicationInitializationContext context)
    {
        
          
        //下发任务通道构建
        DataChannelManage.TaskDataChannel = Channel.CreateUnbounded<ValueTuple<string, List<MeterReadingTelemetryPacketInfo>>>();
         
        //默认初始化表计信息
        var dbContext = context.ServiceProvider.GetRequiredService<EnergySystemScheduledMeterReadingService>();
        await dbContext.InitAmmeterCacheData("V4-Gather-8890");
        await dbContext.InitWatermeterCacheData("V4-Gather-8890");
    }
}