
using Godot;
using Rokojori;
using System.Collections.Generic;
 
namespace Rokojori
{ 
  [Tool]
  [GlobalClass,Icon("res://addons/rokojori_action_library/Icons/UIImage.svg")]
  public partial class NinePatchUIImageType:UIImageType
  { 
    Dictionary<UIImage,UINinePatchMaterial> _materials = new Dictionary<UIImage, UINinePatchMaterial>();

    [ExportGroup( "Nine Patch Pixel Offsets")]
    float _horizontalPixelOffset = 0;
    [Export]
    public float horizontalPixelOffset
    {
      get => _horizontalPixelOffset;
      set { _horizontalPixelOffset = value; onChange.DispatchEvent( null ); }
    }

    float _leftPixelOffset = 0;
    [Export]
    public float leftPixelOffset
    {
      get => _leftPixelOffset;
      set { _leftPixelOffset = value; onChange.DispatchEvent( null ); }
    }

    float _rightPixelOffset = 0;
    [Export]
    public float rightPixelOffset
    {
      get => _rightPixelOffset;
      set { _rightPixelOffset = value; onChange.DispatchEvent( null ); }
    }

    float _verticalPixelOffset = 0;
    [Export]
    public float verticalPixelOffset
    {
      get => _verticalPixelOffset;
      set { _verticalPixelOffset = value; onChange.DispatchEvent( null ); }
    }


    float _topPixelOffset = 0;
    [Export]
    public float topPixelOffset
    {
      get => _topPixelOffset;
      set { _topPixelOffset = value; onChange.DispatchEvent( null ); }
    }

    float _bottomPixelOffset = 0;
    [Export]
    public float bottomPixelOffset
    {
      get => _bottomPixelOffset;
      set { _bottomPixelOffset = value; onChange.DispatchEvent( null ); }
    }


    protected override void _Assign( UIImage image )
    {
      if ( _materials.ContainsKey( image ) )
      {
        return;
      }

      _materials[ image ] = new UINinePatchMaterial();

      image.Material = _materials[ image ];
      
    }

    protected override void _Clear( UIImage image )
    {
      if ( image != null && _materials.ContainsKey( image ) && image.Material == _materials[ image ] )
      {
        image.Material = null;
      }

      _materials.Remove( image );
      
    }

    protected override void _ApplyChange( UIImage image )
    {
      var material = _materials[ image ];

      var borders = new Vector4(
        horizontalPixelOffset + leftPixelOffset,
        horizontalPixelOffset + rightPixelOffset,
        verticalPixelOffset + topPixelOffset,
        verticalPixelOffset + bottomPixelOffset
      );

      material.borders.Set( borders );

    }
  }
}