using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using YoutubeExplode.Models.ClosedCaptions;

namespace FoxTube.Controls
{
    /// <summary>
    /// Control for displaying closed captions
    /// </summary>
    public sealed partial class LiveCaptions : UserControl
    {
        public double Size
        {
            get => text.FontSize;
            set => text.FontSize = value;
        }

        public MediaElement Player { get; set; }
        
        DispatcherTimer timer = new DispatcherTimer() { Interval = TimeSpan.FromMilliseconds(10) };
        ClosedCaption currentCaption = null;

        ClosedCaptionTrack track = null;

        public LiveCaptions()
        {
            InitializeComponent();
            timer.Tick += UpdateCaption;
        }

        private void UpdateCaption(object sender, object e)
        {
            currentCaption = track.Captions.Find(i => i.Offset <= Player.Position && i.Offset + i.Duration > Player.Position);
                       
            if (currentCaption != null)
                text.Text = currentCaption.Text;

            Visibility = currentCaption == null ? Visibility.Collapsed : Visibility.Visible;
        }

        public async void Initialize(ClosedCaptionTrackInfo info)
        {
            track = await new YoutubeExplode.YoutubeClient().GetClosedCaptionTrackAsync(info);

            UpdateCaption(this, null);

            timer.Start();
        }

        public void Close()
        {
            track = null;
            currentCaption = null;
            Visibility = Visibility.Collapsed;
            timer.Stop();
        }
    }
}
