using Microsoft.UI.Xaml.Controls;
using Sonex.Data.Records;
using System;

namespace Sonex.Client.Views;

public sealed partial class AppLogDiagnosticsView : UserControl, IView
{
    private string? _currentKey;
    private bool _hasChanges;

    public event EventHandler? StateChanged;

    public AppLogDiagnosticsView()
    {
        InitializeComponent();
        ClearValues();
    }

    public bool HasChanges => _hasChanges;
    public bool CanSave => CanEdit && HasChanges;
    public bool CanEdit => false;

    public void Clear()
    {
        _currentKey = null;
        ClearValues();
        MarkSaved();
    }

    public void Reload()
    {
        if (string.IsNullOrWhiteSpace(_currentKey))
        {
            Clear();
            return;
        }

        Load(_currentKey);
    }

    public void Load(string key)
    {
        _currentKey = key;
        var result = AppLoggerRecord.Get(key).GetAwaiter().GetResult();

        if (result.Success && result.Item is not null)
        {
            LoadValues(result.Item);
        }
        else
        {
            ClearValues();
            MessageProperty.Value = key;
        }

        MarkSaved();
    }

    public void Save()
    {
        MarkSaved();
    }

    public void MarkChanged()
    {
        _hasChanges = true;
        StateChanged?.Invoke(this, EventArgs.Empty);
    }

    public void MarkSaved()
    {
        _hasChanges = false;
        StateChanged?.Invoke(this, EventArgs.Empty);
    }

    private void LoadValues(AppLoggerRecord log)
    {
        ExceptionTypeProperty.Value = Text(log.ExceptionType);
        MessageProperty.Value = log.Message;
        ReportedMessageProperty.Value = Text(log.ReportedMessage);
        ExceptionProperty.Value = Text(log.Exception);
        ContextProperty.Value = Text(log.Context);
        ExceptionDataProperty.Value = Text(log.ExceptionData);
    }

    private void ClearValues()
    {
        ExceptionTypeProperty.Value = string.Empty;
        MessageProperty.Value = string.Empty;
        ReportedMessageProperty.Value = string.Empty;
        ExceptionProperty.Value = string.Empty;
        ContextProperty.Value = string.Empty;
        ExceptionDataProperty.Value = string.Empty;
    }

    private static string Text(object? value)
    {
        return Convert.ToString(value) ?? string.Empty;
    }
}
