using adas_core.Domain.Enums;
using adas_core.Domain.Models.GroupedObservations;
using Newtonsoft.Json;

namespace adas_core.Domain.Models.SignalR;

/// <summary>
/// Represents a message, typically used for communication or data transfer between components.
/// </summary>
public class Message
{
    public long IdMessage { get; set; }

    public MessageData? Data { get; set; }

    public string? Version { get; set; }

    public List<GroupedField>? GroupedFields { get; set; }

    public string OperationStr
    {
        get => Operation.ToString("g");
        set => Operation = (SubscriptionEnum.Type)Enum.Parse(typeof(SubscriptionEnum.Type), value);
    }

    public SubscriptionEnum.Type Operation { get; set; }


    /// <summary>
    /// Returns a JSON representation of the current object, falling back to the default <see cref="object.ToString"/> implementation if serialization fails.
    /// </summary>
    /// <returns>A JSON-formatted string describing the object, or the result of the base <see cref="object.ToString"/> method if serialization throws an exception.</returns>
    public override string? ToString()
        {
            try
            {
                return JsonConvert.SerializeObject(this, Formatting.None,
                    new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
            }
            catch
            {
                return base.ToString();
            }
        }
}