using APCViewer.Models.Stateless.Methods;
using IFX.Shared;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Serilog.Context;
using System.Text.Json;

namespace APCViewer.Pages;

public class BackgroundPage : PageModel, Models.Properties.IBackgroundPage, IBackgroundPage
{

    protected readonly List<Exception> _Exceptions;
    protected readonly string _AppSettingsURLs;
    protected readonly string _IsEnvironmentProfile;
    protected readonly string _IsPrimaryInstance;
    protected readonly string _Message;
    protected readonly string _WorkingDirectory;
    public List<Exception> Exceptions => _Exceptions;
    public string AppSettingsURLs => _AppSettingsURLs;
    public string IsEnvironmentProfile => _IsEnvironmentProfile;
    public string IsPrimaryInstance => _IsPrimaryInstance;
    public string Message => _Message;
    public string WorkingDirectory => _WorkingDirectory;

    private readonly Serilog.ILogger _Log;
    private readonly Models.Methods.IBackground _BackgroundMethods;

    public BackgroundPage(IsEnvironment isEnvironment, Models.AppSettings appSettings, Singleton.Background background)
    {
        _BackgroundMethods = background;
        _Message = background.Message;
        _AppSettingsURLs = appSettings.URLs;
        _Exceptions = background.Exceptions;
        _Log = Serilog.Log.ForContext<BackgroundPage>();
        _IsEnvironmentProfile = isEnvironment.Profile;
        _WorkingDirectory = background.WorkingDirectory;
        Models.Methods.IBackground backgroundMethods = background;
        _IsPrimaryInstance = backgroundMethods.IsPrimaryInstance().ToString();
    }

    public override string ToString()
    {
        string result = JsonSerializer.Serialize(this, new JsonSerializerOptions() { WriteIndented = true });
        return result;
    }

    public void OnGet(bool? message_clear = null, bool? exceptions_clear = null, bool? set_is_primary_instance = null)
    {
        string? methodName = IMethodName.GetActualAsyncMethodName();
        using (LogContext.PushProperty("MethodName", methodName))
        {
            _Log.Debug("() => ...");
            if (message_clear.HasValue && message_clear.Value)
                _BackgroundMethods.ClearMessage();
            if (exceptions_clear.HasValue && exceptions_clear.Value)
                _Exceptions.Clear();
            if (set_is_primary_instance.HasValue)
            {
                if (set_is_primary_instance.Value)
                    _BackgroundMethods.SetIsPrimaryInstance();
                else
                    _BackgroundMethods.ClearIsPrimaryInstance();
            }
        }
    }

}