using Newtonsoft.Json;

namespace Pilz.UI;


public class PaintingObjectLayering
{

    // <JsonProperty(NameOf(PaintingObject))>
    private readonly PaintingObject _PaintingObject;

    [JsonIgnore]
    public PaintingObject PaintingObject
    {
        get
        {
            return _PaintingObject;
        }
    }

    /// <summary>
    /// Get the current object list from the painting object.
    /// </summary>
    /// <returns>Returns the current object list from the painting object.</returns>
    [JsonIgnore]
    public PaintingObjectList ObjectList
    {
        get
        {
            return PaintingObject.Parent.PaintingObjects;
        }
    }

    /// <summary>
    /// Create a new instance of object layer managing.
    /// </summary>
    /// <param name="obj"></param>
    public PaintingObjectLayering(PaintingObject obj)
    {
        _PaintingObject = obj;
    }

    /// <summary>
    /// Moves the object by the given number of indicies.
    /// </summary>
    /// <param name="count">The number how many objects it should be moved.</param>
    public void MoveObject(int count)
    {
        int oldIndex = ObjectList.IndexOf(PaintingObject);
        int newIndex = oldIndex + count;
        MoveObjectTo(newIndex);
    }

    /// <summary>
    /// Moves the object to the new index.
    /// </summary>
    /// <param name="newIndex"></param>
    public void MoveObjectTo(int newIndex)
    {
        var list = ObjectList;

        // Check & make index valid
        if (newIndex >= ObjectList.Count)
            newIndex = ObjectList.Count - 1;
        else if (newIndex < 0)
        {
            newIndex = 0;
        }

        // Remove object
        list.Remove(PaintingObject);

        // Insert object at new index
        list.Insert(newIndex, PaintingObject);

        // Order all objects again
        list.Layering.OrderAll();
    }

    /// <summary>
    /// Moves the object to the front.
    /// </summary>
    public void BringToTop()
    {
        MoveObjectTo(ObjectList.Count - 1);
    }

    /// <summary>
    /// Moves the object to the back.
    /// </summary>
    public void SendToBack()
    {
        MoveObjectTo(0);
    }

    /// <summary>
    /// Moves the object fordward by one 
    /// </summary>
    public void OneToTop()
    {
        MoveObject(+1);
    }

    /// <summary>
    /// Moves the object backward by one
    /// </summary>
    public void OneToBack()
    {
        MoveObject(-1);
    }

}