using System;
using System.IO;
using System.Text;

/// Append-only text log next to the .exe: logs/ears-YYYYMMDD.log
public static class Logger
{
    private static readonly object _gate = new object();
    private static string _path;
    private static bool _failed;

    public static void Write(string message)
    {
        Write(null, message);
    }

    public static void Write(string tag, string message)
    {
        if (_failed) return;

        string line = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") +
                      (string.IsNullOrEmpty(tag) ? " " : " [" + tag + "] ") +
                      message;

        lock (_gate)
        {
            try
            {
                if (_path == null) _path = Init();
                File.AppendAllText(_path, line + Environment.NewLine, Encoding.UTF8);
            }
            catch (Exception ex)
            {
                _failed = true;   // never let logging crash the app
                Console.WriteLine("[Logger] disabled: " + ex.Message);
            }
        }
    }

    public static void Write(string tag, string format, params object[] args)
    {
        Write(tag, string.Format(format, args));
    }

    public static void Exception(string tag, Exception ex)
    {
        Write(tag, ex.GetType().Name + ": " + ex.Message);
        Write(tag, ex.StackTrace ?? "(no stack)");
    }

    private static string Init()
    {
        string dir = Path.Combine(
            Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
            "logs");

        Directory.CreateDirectory(dir);

        string path = Path.Combine(dir, "ears-" + DateTime.Now.ToString("yyyyMMdd") + ".log");

        File.AppendAllText(path,
            Environment.NewLine +
            "=== session start " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +
            " (" + Environment.OSVersion.Platform + ") ===" + Environment.NewLine,
            Encoding.UTF8);

        return path;
    }
}