using System;
using Windows.Media.Playback;
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 bool IsActive => track != null;

        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()
        {
            timer.Stop();
            track = null;
            currentCaption = null;
            Visibility = Visibility.Collapsed;
        }

        public void Minimize()
        {
            Margin = new Thickness(0, 0, 0, 20);
            text.FontSize = 15;
        }

        public void Maximize()
        {
            Margin = new Thickness(0, 0, 0, 55);
            text.FontSize = 24;
        }
    }
}
