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

namespace Hcs.WebApp.BackgroundServices
{
    public class CampaignManagementState
    {
        public delegate void CampaignStarted(int campaignId, DateTime startedAt);
        public delegate void CampaignProgressStep(int campaignId, int step, int progress);
        public delegate void CampaignEnded(int campaignId, Campaign.CampaignType type, DateTime endedAt, string failureReason);

        private readonly ConcurrentQueue<Campaign> campaigns = new();

        public event Action<Campaign> OnCampaignCreated;
        public event CampaignStarted OnCampaignStarted;
        public event CampaignProgressStep OnCampaignProgressStep;
        public event CampaignEnded OnCampaignEnded;

        public void EnqueueCampaign(Campaign campaign)
        {
            campaigns.Enqueue(campaign);

            OnCampaignCreated?.Invoke(campaign);
        }

        public bool TryDequeueCampaign(out Campaign campaign)
        {
            return campaigns.TryDequeue(out campaign);
        }

        public void InvokeOnCampaignStarted(int campaignId, DateTime startedAt)
        {
            try
            {
                OnCampaignStarted?.Invoke(campaignId, startedAt);
            }
            catch { }
        }

        public void InvokeOnCampaignProgressStep(int campaignId, int step, int progress)
        {
            try
            {
                OnCampaignProgressStep?.Invoke(campaignId, step, progress);
            }
            catch { }
        }

        public void InvokeOnCampaignEnded(int campaignId, Campaign.CampaignType type, DateTime endedAt, string failureReason)
        {
            try
            {
                OnCampaignEnded?.Invoke(campaignId, type, endedAt, failureReason);
            }
            catch { }
        }
    }
}
