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

using DXLib.Utils;

namespace DXLib.Log;

/*
 * Used to serialize the debug log file, which includes a list of log entries.
 */
public class DXLogFile
{
    /* Constants */

    // Maximum list size before pruning
    private const int MaxEntries = 100;

    /* Properties */

    // Time of last file modification
    public DateTimeOffset Modified { get; set; } = DXUtils.Now();

    // All log entries
    public readonly List<DXLogEntry> Entries = [];

    /* Methods */

    // Adds key-only log entry to file
    public void AddEntry( string key )
    {
        DXLogEntry entry = new( key );

        WriteEntry( entry );
    }

    // Adds error message based log entry to file
    public void AddEntry( string key, string error )
    {
        DXLogEntry entry = new( key, error );

        WriteEntry( entry );
    }

    // Adds exception based log entry to file
    public void AddEntry( string key, Exception ex, int code )
    {
        DXLogEntry entry = new( key, ex, code );

        WriteEntry( entry );
    }
    
    // Writes log entry to local cache
    private void WriteEntry( DXLogEntry entry )
    {
        Modified = DXUtils.Now();

        // Save
        Entries.Add( entry );

        // Sort in place (newest first)
        Entries.Sort( (x, y) => y.Timestamp.CompareTo( x.Timestamp ) );

        int count = Entries.Count;

        // Log file full, prune oldest entry
        if ( count > MaxEntries )
        {
            Entries.RemoveAt( count - 1 );
        }
    }
}

//
