using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;


namespace ActionGame.UserInterface.Control
{
    public class Button : IControl
    {
        public IList<IControl> Controls { get; }
        public event GameEventHandler OnClick;
        public delegate void GameEventHandler(object sender, GameEventArgs e);

        public SpriteFont Font { get; set; }
        public String Text { get; set; }
        public Texture2D TexturePressed { get; set; }
        public Texture2D TextureNormal { get; set; }
        public Texture2D TextureSelected { get; set; }
        public SoundEffect PressSound { get; set; }

        private Vector2 textLocation;
        public Boolean IsSelected { get; set; }
        public Boolean IsSelectable { get; }
        private Boolean isPressed;
        private TimeSpan timePressed;
        private Rectangle location;


        public Button()
        {
            this.Controls = new List<IControl>();
            this.isPressed = false;
            this.IsSelectable = true;
        }

        
        public Rectangle Location {
            get
            {
                return this.location;
            }
            set
            {
                this.location = value;

                this.textLocation = GetBestTextLocation();
            }
        }


        public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
        {
            Texture2D texture = null;

            if (this.isPressed) texture = this.TexturePressed;
            else if (this.IsSelected) texture = this.TextureSelected;
            else texture = TextureNormal;

            spriteBatch.Draw(texture, this.Location, Color.White);

            spriteBatch.DrawString(this.Font, this.Text, this.textLocation, Color.Black);
        }


        public void Update(GameTime gameTime)
        {
            if (isPressed)
            {
                if ((gameTime.TotalGameTime - timePressed).TotalSeconds > 0.4)
                {
                    isPressed = false;

                    OnClick?.Invoke(this, new GameEventArgs(gameTime));
                }
            }
        }


        public void Press(GameTime gameTime)
        {
            if(isPressed == false)
            {
                this.timePressed = gameTime.TotalGameTime;
                this.isPressed = true;

                if (PressSound != null)
                {
                    PressSound.Play();
                }
            }
        }


        private Vector2 GetBestTextLocation()
        {
            Vector2 vector = new Vector2(this.Location.X, this.Location.Y);

            vector.Y += 8;
            vector.X += (this.Location.Width/2) - (this.Text.Length * 8);

            return vector;
        }


    }
}
