using BoredCareers.Entities;

namespace BoredCareers.Services.TimerService {
    public class JobCleanupService : BackgroundService {

        private readonly DatabaseService.DatabaseService _db;
        private readonly EmailService _em;

        public JobCleanupService(DatabaseService.DatabaseService db, EmailService em) {
            _db = db;
            _em = em;
        }

        public string Substitue(string message, string subString, string Replacement) {
            for (int i = 0; i < (message.Length - subString.Length); i++) {
                if (message.Substring(i, subString.Length) == subString) {
                    string before = message.Substring(0, i);
                    string after = message.Substring(i + subString.Length);
                    return before + Replacement + after;
                }
            }
            return message;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
            while (!stoppingToken.IsCancellationRequested) {
                try {
                    // Get listing's past expire
                    JobListingDTO[] deletedJobListings = await _db.GetJobListingsPastExipre();

                    // Group them by CompanyID, ListingCount
                    Dictionary<int, int> listingsByCompany = deletedJobListings
                        .GroupBy(l => l.CompanyID)
                        .ToDictionary(g => g.Key, g => g.Count());

                    // Update each company's rating
                    foreach (KeyValuePair<int, int> kvp in listingsByCompany) {
                        Company? comp = await _db.GetCompany(kvp.Key);
                        if (comp != null) {
                            comp.JobsAutoClosed += kvp.Value;
                            await _db.SetCompany(comp);
                        }
                    }

                    // Get each listing
                    foreach (JobListingDTO listing in deletedJobListings) {
                        // Get each Person
                        string[] emails = await _db.GetApplicationResponseEmailFromJobListing(listing.JobListingID);
                        foreach (string email in emails) {
                            // Send Notify Email
                            string emailbody = EmailService.JobAutoClosedBody;
                            //Substitue(emailbody, "@job", listing.JobListingID);

                            await _em.Send(email, EmailService.JobAutoClosedSubject, emailbody);
                        }
                    }

                    // Delete Listing's past expire
                    await _db.DeleteJobListingsPastExipre();
                } catch (Exception e) {
                    Console.WriteLine($"Error: {e.Message}");
                }
                await Task.Delay(TimeSpan.FromHours(2), stoppingToken);
            }
        }
    }

    public class JobListingDTO {
        public int JobListingID { get; set; }
        public int CompanyID { get; set; }
    }
}
