using Infrastructure;
using Newtonsoft.Json;
using OpenAuth.App.ServiceApp;
using Quartz;

namespace OpenAuth.App.OpenJob;

public class FlyTaskJob : IJob
{
    private readonly ManageApp _manageApp;
    private readonly OpenJobApp _openJobApp;

    public FlyTaskJob(ManageApp manageApp, OpenJobApp openJobApp)
    {
        _manageApp = manageApp;
        _openJobApp = openJobApp;
    }

    public Task Execute(IJobExecutionContext context)
    {
        var jobId = context.MergedJobDataMap.GetString(Define.JOBMAPKEY);
        if (string.IsNullOrEmpty(jobId))
        {
            return Task.CompletedTask;
        }
        var job = _openJobApp.Get(jobId);
        if (job == null) return Task.CompletedTask;
        var param = JsonConvert.DeserializeObject<dynamic>(job.JobCallParams);
        var taskId = (string)param.taskId;
        _ = _manageApp.ExecuteFlyTask(taskId);
        _openJobApp.Delete(jobId.Select(c => c.ToString()).ToArray());
        return Task.CompletedTask;
    }
}