using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Microsoft.Advertising.WinRT.UI;
using Windows.UI.Xaml.Media.Imaging;
using Microsoft.Toolkit.Uwp.UI.Controls;
using Microsoft.AppCenter.Analytics;

namespace FoxTube.Controls.Adverts
{
    /// <summary>
    /// Advert which is looks similar to video cards
    /// </summary>
    public sealed partial class CardAdvert : UserControl
    {
        NativeAdsManagerV2 manager = new NativeAdsManagerV2(SecretsVault.AppId, SecretsVault.AdUnitId);
        public NativeAdV2 advert;
        public CardAdvert()
        {
            InitializeComponent();
            manager.AdReady += AdReady;
            manager.ErrorOccurred += ErrorOccurred;
            manager.RequestAd();
        }

        private void ErrorOccurred(object sender, NativeAdErrorEventArgs e)
        {
            (Parent as AdaptiveGridView)?.Items.Remove(this);
            System.Diagnostics.Debug.WriteLine("Error has occured while loading ad");
        }

        private void AdReady(object sender, NativeAdReadyEventArgs e)
        {
            advert = e.NativeAd;
            Initialize();
            e.NativeAd.RegisterAdContainer(grid);
        }

        public void Initialize()
        {
            Visibility = Visibility.Visible;
            title.Text = advert.Title;
            image.Source = new BitmapImage(advert.MainImages.First().Url.ToUri());

            icon.ProfilePicture = advert.AdIcon == null ? null : advert.AdIcon.Source;

            sponsor.Text = Methods.GuardFromNull(advert.SponsoredBy);

            if (string.IsNullOrWhiteSpace(advert.CallToActionText))
                (info.Parent as FrameworkElement).Visibility = Visibility.Collapsed;
            else
                info.Text = advert.CallToActionText;

            desc.Text = string.Empty;

            if (!string.IsNullOrWhiteSpace(advert.Price))
                desc.Text += advert.Price;

            if (!string.IsNullOrWhiteSpace(advert.Rating))
                desc.Text += " " + advert.Rating;

            show.Begin();

            Analytics.TrackEvent("Advert loaded", new Dictionary<string, string> 
            {
                { "Region", SettingsStorage.Region }
            });
        }

        private void Image_ImageOpened(object sender, RoutedEventArgs e)
        {
            showThumb.Begin();
        }
    }
}
