using System;
using UnityEngine;

namespace Alibabacloud.Rum.Unity.Logs
{
    public class UnityLogger : IDiagnosticLogger
    {
        private readonly AlibabacloudOptions _options;

        public UnityLogger(AlibabacloudOptions options)
        {
            _options = options;
        }

        public void Log(AlibabacloudLogLevel logLevel, string message, Exception? exception = null, params object?[] args)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            var formattedMessage = FormatMessage(message, args);
            if (exception != null)
            {
                formattedMessage += $"\n{exception}";
            }

            switch (logLevel)
            {
                case AlibabacloudLogLevel.Debug:
                    Logger.Debug(formattedMessage);
                    break;
                case AlibabacloudLogLevel.Info:
                    // Debug.Log($"[Alibabacloud] {formattedMessage}");
                    Logger.Info(formattedMessage);
                    break;
                case AlibabacloudLogLevel.Warning:
                    // Debug.LogWarning($"[Alibabacloud] {formattedMessage}");
                    Logger.Warn(formattedMessage);
                    break;
                case AlibabacloudLogLevel.Error:
                case AlibabacloudLogLevel.Fatal:
                    // Debug.LogError($"[Alibabacloud] {formattedMessage}");
                    Logger.Error(formattedMessage);
                    break;
            }
        }

        public bool IsEnabled(AlibabacloudLogLevel level)
        {
            if (!_options.Debug)
            {
                return false;
            }

            return level >= _options.DiagnosticLevel;

        }

        private string FormatMessage(string message, params object?[] args)
        {
            try
            {
                return args.Length > 0 ? string.Format(message, args) : message;
            }
            catch (FormatException)
            {
                return message;
            }
        }
    }
}
