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

using System.Diagnostics;

using DXLib.Log;

namespace DXLib.Utils;

/*
 * Provides profiling functionality using a stopwatch to measure and output elapsed time for internal operations.
 */
public static class DXProfiler
{
    /* Properties */
    
    // Current elapsed time
    public static long Elapsed => stopwatch.ElapsedMilliseconds;

    /* Fields */
    private static Stopwatch stopwatch;
    private static long lastTime;

    // Starts/resets profiling timer
    [Conditional( "DEBUG" )]
    public static void Start( bool reset = false )
    {
        // Lazily create
        stopwatch ??= new Stopwatch();

        // Optionally reset
        if ( reset )
        {
            lastTime = 0;
            stopwatch.Reset();
        }

        // Start
        stopwatch.Start();
        Mark( "Start" );
    }

    // Marks profiling time, outputs info
    [Conditional( "DEBUG" )]
    public static void Mark( string label = null, bool stop = false )
    {
        // Optional mark description
        string labelStr = (label == null) ? string.Empty : $"{label} ";

        // Total elapsed time
        long total = stopwatch.ElapsedMilliseconds;

        // Elapsed time since last mark
        long delta = (total - lastTime);

        // 'Foo total:xxx delta:xxx'
        DXLog.Trace( "{0}\t\ttotal:{1} delta:{2}", labelStr, total, delta );

        lastTime = total;

        // Optionally stop profiling
        if ( stop )
        {
            Stop();
        }
    }
    
    // Stops underlying timer
    public static void Stop()
    {
        stopwatch.Stop();
    }
    
    // Resets underlying timer
    public static void Reset()
    {
        stopwatch.Reset();
    }
}

//
