using RobotNet.MapShares.Dtos;
using System.Text.Json;

namespace RobotNet.WebApp.Maps.Models;

public class NodeModel(NodeDto Data) : IDisposable
{
    public Guid Id => Data.Id;
    public Guid MapId => Data.MapId;
    public string Name => Data.Name;
    public double X => Data.X;
    public double Y => Data.Y;
    public double Theta => Data.Theta;
    public string Actions => Data.Actions;
    public double AllowedDeviationXy => Data.AllowedDeviationXy;
    public double AllowedDeviationTheta => Data.AllowedDeviationTheta;

    public event Action? PositionChanged;
    public event Action<bool>? ActivedChanged;
    public event Action<bool>? ErrorChanged;

    public int NumberOfEdgeReference => PositionChanged?.GetInvocationList().Length ?? 0;

    public void UpdatePosition(double x, double y)
    {
        if (Data.X == x && Data.Y == y) return;

        Data.X = x;
        Data.Y = y;
        PositionChanged?.Invoke();
    }
    public void UpdatePosition(double x, double y, double theta)
    {
        if (Data.X == x && Data.Y == y && Data.Theta == theta) return;

        Data.X = x;
        Data.Y = y;
        Data.Theta = theta;
        PositionChanged?.Invoke();
    }

    public void UpdateData(NodeUpdateModel model)
    {
        Data.Name = model.Name;
        Data.AllowedDeviationXy = model.AllowedDeviationXy;
        Data.AllowedDeviationTheta = model.AllowedDeviationTheta;
        Data.Actions = JsonSerializer.Serialize(model.Actions);
        UpdatePosition(model.X, model.Y, model.Theta);
    }

    public void Active() => ActivedChanged?.Invoke(true);
    public void UnActive() => ActivedChanged?.Invoke(false);
    public void SetError(bool state) => ErrorChanged?.Invoke(state);

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}
