using Hcs.WebApp.Data.Hcs;
using System.Collections.Concurrent;

namespace Hcs.WebApp.BackgroundServices
{
    public class DataParsingState
    {
        private readonly ConcurrentQueue<Operation> operationsInQueue = new();
        private readonly HashSet<Operation> operationsInProcess = [];

        public bool Ready { get; set; }

        public event Action<Operation> OnOperationCreated;
        public event OperationStarted OnOperationStarted;
        public event OperationEnded OnOperationEnded;

        public void EnqueueOperation(Operation operation)
        {
            operationsInQueue.Enqueue(operation);

            OnOperationCreated?.Invoke(operation);
        }

        public bool TryDequeueOperation(out Operation operation)
        {
            return operationsInQueue.TryDequeue(out operation);
        }

        public void SetProcessingOperation(Operation operation)
        {
            operationsInProcess.Add(operation);
        }

        public void UnsetProcessingOperation(Operation operation)
        {
            operationsInProcess.Remove(operation);
        }

        public bool HasCampaignOperation(int campaignId)
        {
            return operationsInQueue.Any(x => x.CampaignId == campaignId) || operationsInProcess.Any(x => x.CampaignId == campaignId);
        }

        public void InvokeOnOperationStarted(int operationId, int campaignId, DateTime startedAt)
        {
            try
            {
                OnOperationStarted?.Invoke(operationId, campaignId, startedAt);
            }
            catch { }
        }

        public void InvokeOnOperationEnded(int operationId, int campaignId, DateTime endedAt, string failureReason)
        {
            try
            {
                OnOperationEnded?.Invoke(operationId, campaignId, endedAt, failureReason);
            }
            catch { }
        }
    }
}
