using IRaCIS.Core.Domain;
using IRaCIS.Core.Domain.Share;
using MassTransit;
using MassTransit.Mediator;
using Medallion.Threading;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.MassTransit.Consumer;


public class MasstransiTestCommand
{
    public string value { get; set; }
}

/// <summary>
/// meditor send 的时候，请求流会先到消费者，返回后才会执行后续代码
///          publish  请求流不会先到消费者，发布后，直接执行后续代码
///          
/// </summary>
/// <param name="_userRepository"></param>
public class MasstransitTestConsumer(IRepository<User> _userRepository) : IConsumer<MasstransiTestCommand>
{
    public async Task Consume(ConsumeContext<MasstransiTestCommand> context)
    {

        Console.WriteLine(_userRepository._dbContext.GetHashCode());
        Console.WriteLine("Now is " + DateTime.Now.ToString());
        Console.WriteLine($"MassTransit.Consumer :{context.Message.value}");

        await context.RespondAsync<IResponseOutput>(ResponseOutput.Ok());

    }
}

[ApiExplorerSettings(GroupName = "Institution")]
public class TestMasstransitService : BaseService
{


    public async Task<IResponseOutput> TestMasstransitRequest([FromServices] IMessageScheduler _scheduler,
        [FromServices] IRepository<TestLength> _testLengthRepository,
        [FromServices] IRequestClient<MasstransiTestCommand> _requestClient,
        [FromServices] IScopedClientFactory _clientFactory,
        [FromServices] IScopedMediator _mediatorScoped,
        [FromServices] IMediator _mediator)
    {
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        Console.WriteLine(_testLengthRepository._dbContext.GetHashCode());

        //IScopedMediator  上下文一致，  IMediator上下文不一致

        //通过命令不获取结果  进入消费者后再返回  数据库上下文   不同
        await _mediator.Send(new MasstransiTestCommand { value = "message at " + DateTime.Now.ToString() });

        //通过命令获取结果   进入消费者后再返回  数据库上下文  相同
        var dd = await _mediatorScoped.CreateRequest(new MasstransiTestCommand() { value = "message at " + DateTime.Now.ToString() })
            .GetResponse<IResponseOutput>();

        //发布后，不会立即进入消费者，消费者是另外的线程执行
        await _mediatorScoped.Publish(new MasstransiTestCommand { value = "message at " + DateTime.Now.ToString() });


        //await _scheduler.SchedulePublish(DateTime.Now.AddSeconds(10), new MasstransitHangfireTest() { value = "message at " + DateTime.Now.ToString() });

        return ResponseOutput.Ok();
    }
}






