using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using MegaRobo.Contract;

namespace MegaRobo.RRQuartz
{
    public class JobItemAsync : JobItemBase
    {
        public JobItemAsync()
        {

        }
        public JobItemAsync(JobItemAsync jobItem) : base(jobItem)
        {
            this.ResultAction = jobItem.ResultAction;
            this.ExecuteAction = jobItem.ExecuteAction;
        }

        public JobItemAsync(string name, string title, IConnection targetService, string descr = null, [CallerFilePath] string sourceFilePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0)
            : base(name, title, targetService, descr, sourceFilePath, memberName, sourceLineNumber)
        {

        }

        public JobItemAsync(string name, string title, IConnection targetService, TimeSpan timeout, string descr = null, [CallerFilePath] string sourceFilePath = "", [CallerMemberName] string memberName = "", [CallerLineNumber] int sourceLineNumber = 0)
            : this(name, title, targetService, descr, sourceFilePath, memberName, sourceLineNumber)
        {
            this.Timeout = timeout;
        }

        public Func<Task> ExecuteAction { get; set; }
        public Func<object, Task> ResultAction { get; set; }

        public override async Task OnExecuteActionAsync()
        {
            if(this.ExecuteAction == null) return;
            this.ExecCount++;
            this.Status = JobStatus.HasSend;
            // this.SetStatus(JobStatus.RunSuccess);
            this.UsedTime.Restart();
            await this.ExecuteAction.Invoke();
        }

        public override async void Restart()
        {
            this.ExecCount = 0;
            await this.OnExecuteActionAsync();
        }
    }

    public class JobItemAsync<TMode> : JobItemAsync where TMode : Enum
    {
        public JobItemAsync(TMode mode, string name, string title, IConnection targetService, TimeSpan timeout, string descr = null) : base(name, title, targetService, timeout, descr)
        {
            this.Mode = mode;
        }

        public TMode Mode { get; }
    }
}