using RobotNet.MapShares.Dtos;

namespace RobotNet.WebApp.Maps.Models;

#nullable disable

public class ElementModel : IDisposable
{
    public Guid Id => Element.Id;
    public Guid ModelId => Element.ModelId;
    public Guid NodeId => Element.NodeId;
    public Guid MapId => Element.MapId;
    public string Name => Element.Name;
    public double X => Node.X;
    public double Y => Node.Y;
    public double Theta => Node.Theta;
    public double OffsetX => Element.OffsetX;
    public double OffsetY => Element.OffsetY;
    public bool IsOpen => Element.IsOpen;
    public string Content => Element.Content;

    public event Func<Task> PositionChanged;
    public event Func<Task> OffsetChanged;

    public ElementDto Element { get; private set; }
    public NodeModel Node { get; private set; }

    public ElementModel(ElementDto element, NodeModel node)
    {
        Element = element;
        Node = node;

        Node.PositionChanged += Node_PositionChanged;
    }

    public void Node_PositionChanged() => PositionChanged?.Invoke();

    public void UpdateOffset(double offsetX, double offsetY)
    {
        if (Element.OffsetX == offsetX && Element.OffsetY == offsetY) return;

        Element.OffsetX = offsetX;
        Element.OffsetY = offsetY;
        OffsetChanged?.Invoke();
    }

    public void UpdateElement(ElementDto model)
    {
        Element.Name = model.Name;
        Element.IsOpen = model.IsOpen;
        Element.Content = model.Content;
        UpdateOffset(model.OffsetX, model.OffsetY);
    }

    public void Dispose()
    {
        Node.PositionChanged -= Node_PositionChanged;
        GC.SuppressFinalize(this);
    }
}
