using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Microsoft.Advertising.WinRT.UI;
using Windows.UI.Xaml.Media.Imaging;

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.RequestAd();
        }

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

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

            icon.ProfilePicture = advert.AdIcon.Source;

            if (string.IsNullOrWhiteSpace(advert.SponsoredBy))
                sponsor.Visibility = Visibility.Collapsed;
            else
                sponsor.Text = advert.SponsoredBy;

            if (!string.IsNullOrWhiteSpace(advert.Rating))
                info.Text += $" {advert.Rating}";

            if (string.IsNullOrWhiteSpace(advert.CallToActionText) && string.IsNullOrWhiteSpace(advert.Price))
                desc.Visibility = Visibility.Collapsed;
            else if (!string.IsNullOrWhiteSpace(advert.CallToActionText))
                desc.Text = advert.CallToActionText;
            else
                desc.Text = advert.Price;

            Visibility = Visibility.Visible;
        }
    }
}
