/* 
 * Copyright (c)2009-2025 DemiVision, LLC. All Rights Reserved. The information 
 * herein is the CONFIDENTIAL and PROPRIETARY information of DemiVision, LLC. 
 */

namespace DXLib.Utils;

/*
 * Simple wrapper for MAUI timer that will create a timer and callback a specified method at regular tick intervals.
 */
public class DXTimer
{
    /* Events */

    // Method called back at each tick interval
    public Action Callback { get; init; }

    /* Properties */

    // Tick interval (ms)
    public int Interval { get; init; }

    // Does timer fire once-only or until stopped?
    public bool IsRepeating { get; init; }

    // Is timer currently ticking?
    public bool IsRunning => timer is { IsRunning: true };

    /* Fields */
    private IDispatcherTimer timer;

    /* Methods */

    // Convenience method for starting once-only timer with specified delay
    public static DXTimer Delay( int delay, Action callback )
    {
        DXTimer timerObj = new()
        {
            Callback = callback,
            Interval = delay,
            IsRepeating = false
        };

        timerObj.Start();

        return timerObj;
    }

    // Creates and starts timer at preset interval
    public void Start()
    {
        // Create
        timer = Application.Current?.Dispatcher.CreateTimer();

        if ( timer != null )
        {
            // Configure
            timer.Interval = TimeSpan.FromMilliseconds( Interval );
            timer.IsRepeating = IsRepeating;

            timer.Tick += ( sender, evt ) => Tick();

            // Start
            timer.Start();
        }
    }

    // Invokes timer callback on main UI thread
    private void Tick()
    {
        MainThread.BeginInvokeOnMainThread( () =>
        {
            Callback?.Invoke();
        });
    }

    // Manually stops timer
    public void Stop()
    {
        timer.Stop();
    }
}

//
