using FoxTube.Controls.Adverts;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace FoxTube.Pages
{
    /// <summary>
    /// Items cards container
    /// </summary>
    public sealed partial class VideoGrid : Page
    {
        public int Columns
        {
            get { return cols; }
            set
            {
                cols = value;
                UpdateGrid();
            }
        }
        private int cols = 1;
        public int Count => Children.Count;
        public bool IsRelatedVideos { get; set; } = false;
        public List<UIElement> Children { get; } = new List<UIElement>();

        public VideoGrid()
        {
            InitializeComponent();
        }

        public void Add(UIElement card)
        {
            (grid.Children[Count % cols + 1] as StackPanel).Children.Add(card);
            Children.Add(card);

            if ((Children.Count - 5) % 25 == 0 && !SecretsVault.AdsDisabled)
            {
                CardAdvert advert = new CardAdvert(IsRelatedVideos);
                (grid.Children[Count % cols + 1] as StackPanel).Children.Add(advert);
                Children.Add(advert);
            }

            empty.Visibility = Visibility.Collapsed;
        }

        public void Clear()
        {
            for (int k = 1; k <= 5; k++)
                (grid.Children[k] as StackPanel).Children.Clear();

            empty.Visibility = Visibility.Visible;
        }

        public void DeleteItem(FrameworkElement item)
        {
            Children.Remove(item);
            UpdateGrid();
        }

        void UpdateGrid()
        {
            for (int k = 1; k <= 5; k++)
                (grid.Children[k] as StackPanel).Children.Clear();

            for (int k = 0; k < Count; k++)
                (grid.Children[k % cols + 1] as StackPanel).Children.Add(Children[k]);

            for (int k = 0; k < cols; k++)
                grid.ColumnDefinitions[k].Width = new GridLength(1, GridUnitType.Star);

            for (int k = cols; k < 5; k++)
                grid.ColumnDefinitions[k].Width = new GridLength(0);
        }

        private void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.NewSize.Width >= 1600 && Columns != 5)
                Columns = 5;
            else if (e.NewSize.Width >= 1200 && e.NewSize.Width < 1600 && Columns != 4)
                Columns = 4;
            else if (e.NewSize.Width >= 900 && e.NewSize.Width < 1200 && Columns != 3)
                Columns = 3;
            else if (e.NewSize.Width >= 550 && e.NewSize.Width < 900 && Columns != 2)
                Columns = 2;
            else if (e.NewSize.Width < 550 && Columns != 1)
                Columns = 1;
        }
    }
}
