module scheduled_jobs;

import scheduled;
import std.datetime;
import slf4d;

void startScheduledJobs() {
	JobSchedule analyticsSchedule = new FixedIntervalSchedule(
		days(1),
		Clock.currTime(UTC()) + seconds(5)
	);

	JobScheduler jobScheduler = new TaskPoolScheduler();
	
	jobScheduler.addJob(() {
		// Clear old analytics data from profiles.
		import profile.data;
		import profile.data_impl_sqlite;
		import profile.model;
		FileSystemProfileRepository.doForAllUserProfiles(
			(Profile profile, ProfileRepository profileRepo) {
				ProfileDataSource ds = profileRepo.getDataSource(profile);
				auto props = ds.getPropertiesRepository().findAll();
				bool shouldDelete = false;
				foreach (prop; props) {
					import std.string : startsWith;
					if (startsWith(prop.property, "analytics")) {
						shouldDelete = true;
						break;
					}
				}
				if (shouldDelete) {
					ds.getPropertiesRepository().deleteAllByPrefix("analytics");
					infoF!"Deleted all old \"analytics\" properties for user %s profile %s."(
						profile.username, profile.name
					);
				}
			}
		);
		
	}, analyticsSchedule);

	// Add a scheduled job to regularly check for and create recurring transaction drafts. 
	jobScheduler.addJob(() {
		import profile.data;
		import profile.data_impl_sqlite;
		import profile.model;
		import transaction.service;
		import std.datetime.stopwatch;
		StopWatch sw = StopWatch(AutoStart.yes);
		FileSystemProfileRepository.doForAllUserProfiles((Profile profile, ProfileRepository profileRepo) {
			ProfileDataSource ds = profileRepo.getDataSource(profile);
			updateRecurringTransactionScheduling(ds);
		});
		sw.stop();
		long elapsedTimeMs = sw.peek.total!"msecs";
		if (elapsedTimeMs > 1000) {
			warnF!"Took more than 1 second to process recurring transactions: %d ms."(elapsedTimeMs);
		}
	}, new FixedIntervalSchedule(minutes(1), Clock.currTime(UTC())));

	jobScheduler.start();
}