using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Bellwether.UIComponent
{
    public class RecAnimation : Image
    {
        public RecAnimation()
        {
            RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.HighQuality);
            Loaded += RecAnimation_Loaded;
            Unloaded += RecAnimation_Unloaded;

            animationTimer = new Timer(100);
            animationTimer.Elapsed += AnimationTimer_Elapsed;
        }

        private void RecAnimation_Unloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            animationTimer?.Stop();
        }

        private void RecAnimation_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            PreLoad();
            animationTimer?.Start();
        }

        private Timer animationTimer;
        private int aniIndex = 0;
        private BitmapImage[] bitmaps;

        private void PreLoad()
        {
            bitmaps = new BitmapImage[150];
            //for (int index = 0; index < 150; index++)
            //{
            //    var sourceString = string.Format("pack://application:,,,/Bellwether;component/Images/Recs/Comp 1{0:000}.png", index);
            //    bitmaps[index] = new BitmapImage(new Uri(sourceString));
            //}
        }

        private void AnimationTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //var sourceString = $"pack://application:,,,/Bellwether;component/Images/Recs/Comp 1{aniIndex,3,0}.png";
            var sourceString = string.Format("pack://application:,,,/Bellwether;component/Images/Recs/Comp 1{0:000}.png", aniIndex++);
            if (aniIndex > 149)
            {
                aniIndex = 0;
            }
            Dispatcher.Invoke(() => {
                //this.Source = bitmaps[aniIndex++];
                this.Source = new BitmapImage(new Uri(sourceString));
            });
        }
    }
}