using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sonex.Client.UserControls.DataGridView
{
    public sealed partial class DataGridView
    {

        public sealed class SmoothStepScroller
        {
            private readonly DispatcherTimer _timer;
            private readonly ScrollBar _scroll;
            private double _step; // ile jednostek na tick

            private int _direction; // -1 = start, +1 = end

            public SmoothStepScroller(ScrollBar scroll, int step = 1, int intervalMs = 16)
            {
                _scroll = scroll;
                _step = Math.Max(1, step);

                _timer = new DispatcherTimer();
                _timer.Interval = TimeSpan.FromMilliseconds(intervalMs);
                _timer.Tick += OnTick;
            }

            public void GoToStart(double intervalMs = 16, double step = 1)
            {
                _step = Math.Max(1, step);
                _timer.Interval = TimeSpan.FromMilliseconds(intervalMs);
                _direction = -1;
                if (!_timer.IsEnabled)
                {
                    _timer.Interval = TimeSpan.FromMilliseconds(600);
                    _timer.Start();
                }
            }

            public void GoToEnd(double intervalMs = 16, double step = 1)
            {
                _step = Math.Max(1, step);
                _timer.Interval = TimeSpan.FromMilliseconds(intervalMs);
                _direction = 1;
                if (!_timer.IsEnabled)
                {
                    _timer.Interval = TimeSpan.FromMilliseconds(600);
                    _timer.Start();
                }
            }

            public void Stop()
            {
                if (_timer.IsEnabled)
                    _timer.Stop();
            }

            private void OnTick(object? sender, object e)
            {
                if (_direction == 0) return;

                double newValue = _scroll.Value + (_direction * _step);

                if (newValue <= _scroll.Minimum)
                {
                    _scroll.Value = _scroll.Minimum;
                    Stop();
                    return;
                }

                if (newValue >= _scroll.Maximum)
                {
                    _scroll.Value = _scroll.Maximum;
                    Stop();
                    return;
                }

                _scroll.Value = newValue;
                //_timer.Interval = TimeSpan.FromMilliseconds(_timer.Interval.TotalMilliseconds * 0.8d);
                //_timer.Start();
            }
        }
    }
}
