using Microsoft.Advertising.WinRT.UI;
using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace FoxTube.Controls.Adverts
{
    public sealed partial class PlayerAdvert : UserControl
    {
        NativeAdsManagerV2 manager = new NativeAdsManagerV2(SecretsVault.AppId, SecretsVault.AdUnitId);
        NativeAdV2 advert;
        
        DispatcherTimer timer = new DispatcherTimer()
        {
            Interval = TimeSpan.FromMilliseconds(10000)
        };
        public PlayerAdvert()
        {
            InitializeComponent();

            manager.AdReady += AdReady;
            manager.ErrorOccurred += ErrorOccurred;

            timer.Tick += (s, e) =>
            {
                timer.Stop();
                hide.Begin();
            };
        }

        private void ErrorOccurred(object sender, NativeAdErrorEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("Error has occured while loading ad");
        }

        private void AdReady(object sender, NativeAdReadyEventArgs arg)
        {
            advert = arg.NativeAd;

            title.Text = advert.Title;
            description.Text = Methods.GuardFromNull(advert.Description);

            if (advert.AdIcon != null)
            {
                grid.Children.Insert(0, advert.AdIcon);

                advert.AdIcon.HorizontalAlignment = HorizontalAlignment.Left;
                advert.AdIcon.Margin = new Thickness(4);
                advert.AdIcon.Width = double.NaN;
                advert.AdIcon.Height = double.NaN;

                advert.AdIcon.SizeChanged += (s, e) => grid.ColumnDefinitions[0].Width = new GridLength(advert.AdIcon.ActualWidth + 8);
            }

            cta.Content = Methods.GuardFromNull(advert.CallToActionText);
            cta.Visibility = string.IsNullOrWhiteSpace(advert.CallToActionText) ? Visibility.Collapsed : Visibility.Visible;

            info.Text += advert.Price;
            info.Text += " " + advert.Rating;

            if (cta.Visibility == Visibility.Collapsed)
                advert.RegisterAdContainer(grid);
            else
                advert.RegisterAdContainer(grid, new List<FrameworkElement> { cta });

            timer.Start();
            show.Begin();
        }

        public void PushAdvert()
        {
            manager.RequestAd();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            timer.Stop();
            hide.Begin();
        }
    }
}
