using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.RegisterServices;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Builder;
using Senparc.Weixin.AspNet;
using Senparc.Weixin.WxOpen;
using Senparc.CO2NET.AspNet;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Options;
using Senparc.CO2NET;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using XF.Domain.Options;

namespace Hotline.WeChat;
public static class ServiceCollectionExtensions
{
    private readonly static string KeyName = "WxOpenAppId";
    public static IServiceCollection AddWeChatService(this IServiceCollection services, IConfiguration configuration)
    {
        var config = configuration.GetSection(nameof(SenparcWeixinSetting));
        if (config.GetSection(KeyName).Value == null) return services;
        services.Configure<Configurations.SenparcWeixinSetting>(d => configuration.GetSection(nameof(SenparcWeixinSetting)).Bind(d));
        services.AddMemoryCache();
        services.AddSenparcWeixin(configuration);
        return services;
    }

    public static void UseWeChat(this WebApplication app)
    {
        if (app.Configuration.GetSection(nameof(SenparcWeixinSetting)).GetSection(KeyName).Value == null) return;
        var registerService = app.UseSenparcWeixin(app.Environment,
        null /* 不为 null 则覆盖 appsettings  中的 SenpacSetting 配置*/,
        null /* 不为 null 则覆盖 appsettings  中的 SenpacWeixinSetting 配置*/,
        register => { },
        (register, weixinSetting) =>
        {
            //注册公众号信息（可以执行多次，注册多个小程序）
            register.RegisterWxOpenAccount(weixinSetting, "微信小程序");
        });
    }
}
