﻿using System;
using System.Runtime.InteropServices;
using UnityEngine;

namespace BlackBox
{
    public static class AndroidHandler
    {
		public const string PLUGIN_NAME_BLACKBOX_CORE = "blackbox-core";
		
		public const int ERROR_TYPE_CRASH = 0;
		public const int ERROR_TYPE_EXCEPTION = 1;
		public const int ERROR_TYPE_ASSERT = 2;
		public const int ERROR_TYPE_UNKNOWN = 3;
		
		public const string SOURCE_CSHARP = "csharp";

        [DllImport(PLUGIN_NAME_BLACKBOX_CORE, CallingConvention = CallingConvention.Cdecl)]
        public static extern void bbx_process_crash_stack_trace(string content, int error, string source);

        public static int get_error_type(LogType type)
        {
	        switch (type)
	        {
		        case LogType.Exception:
			        return ERROR_TYPE_EXCEPTION;
		        case LogType.Assert:
			        return ERROR_TYPE_ASSERT;
		        default:
			        return ERROR_TYPE_UNKNOWN;
	        }
        }

        public static void process_crash_stack_trace(string content, LogType type)
        {
	        bbx_process_crash_stack_trace(content, get_error_type(type), SOURCE_CSHARP);
        }

        public static void Initialize()
        {
			Debug.Log("Init c# unhandled exception");
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
        }
        private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
			Debug.Log("An unhandled exception appear from c#");
            string message;
            int error_type = ERROR_TYPE_UNKNOWN;
            if (e.ExceptionObject is Exception ex)
            {
                 message = $"Unhandled exception:\n{ex.Message}";
                 error_type = ERROR_TYPE_EXCEPTION;
            }
            else
            {
                message = $"Unknown error:\n{e.ExceptionObject}";
            }
			Debug.Log($"Message is {message}");
            bbx_process_crash_stack_trace(message, error_type, SOURCE_CSHARP);
        }
    }
}