using Microsoft.Xna.Framework;
using MonoGame.FourEngine.Collections;
using MonoGame.FourEngine.Components;
using MonoGame.FourEngine.Resources;
using System.Collections.Generic;

namespace MonoGame.FourEngine.Entities
{
    public abstract class TextEntity : Entity
    {
        public TextComponent Component { get; protected set; }

        protected abstract FontDefinition FontDefinition { get; }

        public bool Visibility
        {
            get => _visibility;
            set
            {
                _visibility = value;
                OnVisibilityChanged(value);
            }
        }
        private bool _visibility;

        public Point Position
        {
            get => Component.Position;
            set => Component.Position = value;
        }

        public string Text
        {
            get => Component.Text;
            set => Component.Text = value;
        }

        public Color Color
        {
            get => Component.Color;
            set => Component.Color = value;
        }

        public int Width => Component.Width;
        public int Height => Component.Height;

        public ICollection<TextDrawHandler> Transformations { get; private set; }

        public TextEntity()
        {
            CreateComponent();
            Visibility = true;
            Transformations = new SimpleObservableCollection<TextDrawHandler>(OnTransformationAdd, OnTransformationRemove);
        }

        protected virtual void CreateComponent()
        {
            Components.Add(Component = new TextComponent(FontDefinition));
        }

        public virtual void OnPrimaryClick(ClickedEventArgs args) { }

        public virtual void OnSecondaryClick(ClickedEventArgs args) { }

        private void OnTransformationAdd(TextDrawHandler handler)
        {
            Component.BeforeDraw += handler;
        }

        private void OnTransformationRemove(TextDrawHandler handler)
        {
            Component.BeforeDraw -= handler;
        }

        protected virtual void OnVisibilityChanged(bool value)
        {
            if (value)
            {
                if (!Components.Contains(Component))
                    Components.Add(Component);
            }
            else
            {
                if (Components.Contains(Component))
                    Components.Remove(Component);
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            Transformations.Clear();
        }
    }
}