
using Godot;
using Rokojori;
using System.Collections.Generic;
using System.Linq;

namespace Rokojori
{ 
  [Tool]
  [GlobalClass,Icon("res://addons/rokojori_action_library/Icons/UIImage.svg")]
  public abstract partial class UIImageType:Resource
  { 
    public readonly EventSlot<Null> onChange = new EventSlot<Null>();
    List<UIImage> _images = new List<UIImage>();
    

    public UIImageType()
    {
      onChange.AddAction( a => ApplyChanges() );
    }

    public void Assign( UIImage image )
    {
      if ( ! _images.Contains( image ) )
      {
        _images.Add( image );
      }

      _Assign( image );
      _ApplyChange( image );
    }

    public void Clear( UIImage image )
    {
      _images.Remove( image );
      _Clear( image );
    }

    public void Sync( UIImage image )
    {
      _Sync( image );
    }

    protected virtual void _Sync( UIImage image )
    {

    }

    public void ApplyChanges()
    {
      _images.ForEach( i => _ApplyChange( i ) );
    } 

    public virtual UIColor GetUIStyleColorProperty( UIStyleColorProperty property, string shaderPropertyName )
    {
      return null;
    }

    public virtual UINumber GetUIStyleNumberProperty( UIStyleNumberProperty property, string shaderPropertyName )
    {
      return null;
    }

    protected virtual void _ApplyChange( UIImage image )
    {

    }     

    protected virtual void _Assign( UIImage image )
    {

    } 

    protected virtual void _Clear( UIImage image )
    {
      
    } 

    public virtual string[] GetColorShaderProperties()
    {
      return [];
    }

    public virtual string[] GetNumberShaderProperties()
    {
      return [];
    }

    protected UIColor GetUIColor( UIColor member, UIImage parent, string name )
    {
      if ( member != null )
      {
        return member;
      }

      var style = parent.parentStyle;

      if ( style == null )
      {
        return null;
      }
      
      var colorProperty = style.colorProperties.Find( c => c.colorPropertyName.propertyName == name );
      
      return colorProperty == null ? null : colorProperty.color;
    }

    
    protected void AssignColor( UIImage image, CustomMaterialProperty<Color> colorProperty, UIColor memberColor )
    {
      image.CopyColorShaderPropertyFrom( colorProperty, GetUIColor( memberColor, image, colorProperty.propertyName ) );
    }

  }
}