using CloudGaming.Code.Monitor;
using CloudGaming.DtoModel.Other;

using Quartz;

using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudGaming.Code.AppExtend
{

    /// <summary>
    /// 定时使用
    /// </summary>
    public abstract class AppJobBase : IJob
    {
        /// <summary>
        /// 
        /// </summary>
        protected readonly IServiceScopeFactory scopeFactory;
        public AppJobBase(IServiceScopeFactory scopeFactory)
        {
            this.scopeFactory = scopeFactory;
        }

        public Task Execute(IJobExecutionContext context)
        {
            if (AppConfigurationExtend.AppConfigs != null && AppConfigurationExtend.AppConfigs.Count > 0)
            {
                var appConfigs = AppConfigurationExtend.AppConfigs.Where(it => it.Key != "default")
                 .Select(it => it.Value)
                 .ToList();

                // 为每个项目启动一个独立的任务
                foreach (var appConfig in appConfigs)
                {


                    _ = Task.Run(() => AppConfigProcessLoop(appConfig));
                }
            }
            return Task.CompletedTask;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="appConfig"></param>
        /// <returns></returns>
        public async Task AppConfigProcessLoop(AppConfig appConfig)
        {
            AppMonitorInfo appMonitorInfo = MonitorExtend.AppMonitorConfigs.GetOrAdd(appConfig.Identifier, new AppMonitorInfo());
            using var scope = scopeFactory.CreateScope();
            var scopedProvider = scope.ServiceProvider;
            var app = scopedProvider.GetRequiredService<AppConfig>();
            appConfig.ToAppConfig(app);
            CloudGamingBase cloudGamingBase = new CloudGamingBase(scopedProvider);
            await AppConfigProcessLoop(appConfig, appMonitorInfo, scopedProvider, cloudGamingBase);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="appConfig"></param>
        /// <param name="appMonitorInfo"></param>
        /// <param name="serviceProvider"></param>
        /// <param name="cloudGamingBase"></param>
        /// <returns></returns>
        public abstract Task AppConfigProcessLoop(AppConfig appConfig, AppMonitorInfo appMonitorInfo, IServiceProvider serviceProvider, CloudGamingBase cloudGamingBase);

    }
}
