namespace Guru
{
    using System.Collections.Generic;
    using UnityEngine;
    using Firebase.Crashlytics;
    using System;
    using System.Linq;
    
    public class GuruRepoter
    {
        private static bool _isReady;
        
        /// <summary>
        /// 捕获列表
        /// </summary>
        private static List<LogType> _catchFilter = new List<LogType>()
        {
            LogType.Exception,
        };
        
        /// <summary>
        /// 上报列表
        /// </summary>
        private static List<LogType> _logFilter = new List<LogType>()
        {
            LogType.Error,
            LogType.Assert,
        };

        public static void Install()
        {
            _isReady = true;
            Crashlytics.IsCrashlyticsCollectionEnabled = true;
            
            Application.logMessageReceived += OnReceivedMessage;
            Application.logMessageReceivedThreaded += OnReceivedMessage;
        }

        private static void CheckReady()
        {
            if (_isReady) return;
            Install();
        }


        private static string ToLogTypeString(LogType type)
        {
            switch (type)
            {
                case LogType.Exception: return "ex";
                case LogType.Error: return "e";
                case LogType.Warning: return "w";
            }
            return "i";
        }


        private static void OnReceivedMessage(string condition, string stackTrace, LogType type)
        {
            
            string msg = $"{DateTime.Now:yy-MM-dd HH:mm:ss} [{ToLogTypeString(type)}] {condition}\n{stackTrace}";
            
            if (_catchFilter.Contains(type))
            {
                LogException(msg);
            }
            else if(_logFilter.Contains(type))
            {
                Log(msg);
            }
        }

        public static void LogException(Exception ex)
        {
            CheckReady();
            Crashlytics.LogException(ex);
        }

        public static void LogException(string msg)
        {
            CheckReady();
            Crashlytics.LogException(new Exception(msg));
        }

        public static void Log(string msg)
        {
            CheckReady();
            Crashlytics.Log(msg);
        }
    }
}