using System;
using System.Threading.Tasks;
using Serilog;
using TINK.Settings;
namespace TINK.ViewModel
{
///
/// Performs a periodic update.
///
public class PollingUpdateTaskManager : IPollingUpdateTaskManager
{
/// Action which performs an update.
private Action UpdateAction { get; }
/// Reference on the current polling task
private PollingUpdateTask UpdateTask { get; set; }
///
/// Gets or sets polling parameters.
///
private PollingParameters PollingParameters { get; set; }
/// Prevents an invalid instance to be created.
private PollingUpdateTaskManager()
{ }
/// Constructs a update manager object.
/// Name of the child class. For logging purposes.
///
public PollingUpdateTaskManager(
Action updateAction)
{
UpdateAction = updateAction ?? throw new ArgumentException(
$"Can not construct {GetType().Name}- obect. Argument {nameof(updateAction)} must not be null.");
}
///
/// Invoked when page is shown.
/// Actuates and awaits the first update process and starts a task wich actuate the subseqent update tasks.
///
/// Parametes holding polling periode, if null last parameters are used if available.
public async Task StartUpdateAyncPeridically(PollingParameters pollingParameters = null)
{
if (UpdateTask != null)
{
Log.Error($"Call to stop periodic update task missed in context {GetType().Name} at {DateTime.Now}.");
// Call of StopUpdatePeriodically missed.
// Terminate running polling update task before starting a new one
await UpdateTask.Terminate();
}
if (pollingParameters != null)
{
// Backup polling parameter for purposee of restart.
PollingParameters = pollingParameters;
}
if (PollingParameters == null)
{
// No polling parameters avaialable.
Log.Error($"Can not start polling. No parameters available.");
return;
}
if (!PollingParameters.IsActivated)
{
// Automatic supdate is switched off.
Log.ForContext().Debug($"Automatic update is off, context {GetType().Name} at {DateTime.Now}.");
return;
}
UpdateTask = new PollingUpdateTask(
UpdateAction,
PollingParameters.Periode);
}
///
/// Invoked when pages is closed/ hidden.
/// Stops update process.
///
public async Task StopUpdatePeridically()
{
if (UpdateTask == null)
{
// Nothing to do if there is no update task pending.
return;
}
await UpdateTask.Terminate();
UpdateTask = null;
}
}
}