namespace OrderPROPrint.Forms;

public partial class LogForm : Form
{
    private static LogForm? _instance;
    private static readonly List<string> _logEntries = new();
    private static readonly object _logLock = new();

    public LogForm()
    {
        InitializeComponent();
    }

    public static void Log(string message)
    {
        var entry = $"[{DateTime.Now:HH:mm:ss}] {message}";

        lock (_logLock)
        {
            _logEntries.Add(entry);
            if (_logEntries.Count > 500)
                _logEntries.RemoveAt(0);
        }

        if (_instance != null && !_instance.IsDisposed)
        {
            try
            {
                _instance.Invoke(() => _instance.AppendLog(entry));
            }
            catch { }
        }
    }

    public static void ShowInstance()
    {
        if (_instance == null || _instance.IsDisposed)
        {
            _instance = new LogForm();

            lock (_logLock)
            {
                foreach (var entry in _logEntries)
                {
                    _instance.AppendLog(entry);
                }
            }
        }

        _instance.Show();
        _instance.BringToFront();
    }

    private void AppendLog(string text)
    {
        txtLog.AppendText(text + Environment.NewLine);
    }

    private void BtnClear_Click(object sender, EventArgs e)
    {
        txtLog.Clear();
        lock (_logLock)
        {
            _logEntries.Clear();
        }
    }

    private void BtnCopy_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(txtLog.Text))
        {
            Clipboard.SetText(txtLog.Text);
        }
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.UserClosing)
        {
            e.Cancel = true;
            Hide();
        }
        else
        {
            base.OnFormClosing(e);
        }
    }
}
