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

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

            manager.AdReady += AdReady;
            manager.ErrorOccurred += ErrorOccurred;
            manager.RequestAd();
        }

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

        private void AdReady(object sender, NativeAdReadyEventArgs e)
        {
            advert = e.NativeAd;
            Initialize();
            if(cta.Visibility == Visibility.Collapsed)
                e.NativeAd.RegisterAdContainer(grid);
            else
                e.NativeAd.RegisterAdContainer(grid, new List<FrameworkElement> { cta });
        }

        private void Initialize()
        {
            title.Text = advert.Title;
            description.Text = Methods.GuardFromNull(advert.Description);
            icon.ProfilePicture = advert.AdIcon == null ? null : advert.AdIcon.Source;

            privacy.NavigateUri = advert.PrivacyUrl.ToUri();
            privacy.Content = advert.PrivacyUrl;
            privacy.Visibility = string.IsNullOrWhiteSpace(advert.PrivacyUrl) ? Visibility.Collapsed : Visibility.Visible;

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

            meta.Text += advert.Price;
            meta.Text += " " + advert.Rating;
            meta.Visibility = string.IsNullOrWhiteSpace(meta.Text) ? Visibility.Collapsed : Visibility.Visible;

            Visibility = Visibility.Visible;
        }
    }
}
