using System;
using System.Collections.Generic;
using System.Linq;

namespace ActionGame.UserInterface.Control
{
    public class ControlCollection : List<IControl>
    {

        private IList<IControl> GetSelectable()
        {
            var selectables = (IList<IControl>)this.Where(x => x.IsSelectable).ToList();

            return selectables;
        }


        public void UnselectAll()
        {
            IList<IControl> items = GetSelectable();

            foreach(IControl item in items)
            {
                item.IsSelected = false;
            }
        }
        

        public IControl GetSelected()
        {
            IList<IControl> items = GetSelectable();

            foreach (IControl item in items)
            {
                if(item.IsSelected)
                {
                    return item;
                }
            }

            return null;
        }


        public void Select(IControl control)
        {
            if (control.IsSelectable)
            {
                UnselectAll();

                control.IsSelected = true;
            }
        }

        
        public void SelectNext()
        {
            if (this.Count == 0) return;

            IList<IControl> items = GetSelectable();
            IControl current = GetSelected();

            if (items.Count == 0) return;

            if(current == null)
            {
                items[0].IsSelected = true;
            }
            else
            {
                Int32 index = items.IndexOf(current);
                index++;

                if(index >= items.Count)
                {
                    index = 0;
                }

                UnselectAll();

                items[index].IsSelected = true;
            }
        }


        public void SelectPrev()
        {
            if (this.Count == 0) return;

            IList<IControl> items = GetSelectable();
            IControl current = GetSelected();

            if (items.Count == 0) return;

            if (current == null)
            {
                items[0].IsSelected = true;
            }
            else
            {
                Int32 index = items.IndexOf(current);
                index--;

                if (index < 0)
                {
                    index = items.Count - 1;
                }

                UnselectAll();

                items[index].IsSelected = true;
            }
        }


        public Int32 IndexOfSelected()
        {
            IList<IControl> items = GetSelectable();

            var search = items.Where(x => x.IsSelected).ToList();

            if(search.Count == 0)
            {
                return -1;
            }

            var item = search[0];

            Int32 index = this.IndexOf(item);

            return index;
        }


    }
}
