using System;
using System.Diagnostics;

namespace RebootKit.Engine.Foundation {
    public enum LogLevel {
        Info,
        Debug,
        Warning,
        Error
    }

    public readonly struct Logger {
        private readonly string _name;

        public Logger(string name) {
            _name = name;
        }

        public void Log(LogLevel level, string message) {
            switch (level) {
                case LogLevel.Info:
                    UnityEngine.Debug.Log(FormatMessage(level, _name, message, true));
                    break;
                case LogLevel.Debug:
                    UnityEngine.Debug.Log(FormatMessage(level, _name, message, true));
                    break;
                case LogLevel.Warning:
                    UnityEngine.Debug.LogWarning(FormatMessage(level, _name, message, true));
                    break;
                case LogLevel.Error:
                    UnityEngine.Debug.LogError(FormatMessage(level, _name, message, true));
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(level), level, null);
            }
        }

        [Conditional(RConsts.BuildFlagDebug)]
        public void Info(string message) {
            Log(LogLevel.Info, message);
        }

        [Conditional(RConsts.BuildFlagDebug)]
        public void Debug(string message) {
            Log(LogLevel.Debug, message);
        }

        [Conditional(RConsts.BuildFlagDebug)]
        public void Warning(string message) {
            Log(LogLevel.Warning, message);
        }

        public void Error(string message) {
            Log(LogLevel.Error, message);
        }

        private static string FormatMessage(LogLevel level, string name, string message, bool richText) {
            if (!richText) {
                string prefix = level switch {
                    LogLevel.Info => "",
                    LogLevel.Debug => "[DEBUG]",
                    LogLevel.Warning => "[WARNING]",
                    LogLevel.Error => "[ERROR]",
                    _ => throw new ArgumentOutOfRangeException(nameof(level), level, null)
                };
                return $"{prefix}[{name}] {message}";
            }

            switch (level) {
                case LogLevel.Info:
                    return $"[<b>{name}</b>] {message}";
                case LogLevel.Debug:
                    return $"[D][<b>{name}</b>] <color=#ffffff>{message}</color>";
                case LogLevel.Warning:
                    return $"[W][<b>{name}</b>] <color=#ffffff>{message}</color>";
                case LogLevel.Error:
                    return $"[<b><color=#ff0000>ERROR</color></b>][<b>{name}</b>] <color=#ffffff>{message}</color>";
                default:
                    throw new ArgumentOutOfRangeException(nameof(level), level, null);
            }

            return "";
        }
    }
}