﻿#region Header

// Copyright (c) 2025 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.

#endregion

#if UNITY_STANDALONE
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;

namespace BlackBox
{
    public class IssueReporter
    {
        private HotKey IssueReporterKey;
        private string IssueDataPath;
        public void Initialize()
        {
            var HotkeyString = Marshal.PtrToStringAnsi(PluginAPI.blackbox_config_get_issue_reporter_hotkey());
            if (string.IsNullOrEmpty(HotkeyString))
            {
                Logger.Log("Cannot read issue reporter button configuration. Please check BlackBox.ini settings!!!");
            }
            else
            {
                IssueReporterKey = DeserializeInputChord(HotkeyString);
                Logger.Log($"Issue reporter button config {HotkeyString}");
            }
            IssueDataPath = Path.Combine(Application.persistentDataPath, "Issues");
        }

        public void Update()
        {
            if (PluginAPI.bbx_config_get_enable_issue_reporter() && IssueReporterKey.IsValid() && IssueReporterKey.WasPressed())
            {
                Logger.Log("Issue reporter button pressed");
                OnIssueReporterTriggerred();
            }
        }

        private void OnIssueReporterTriggerred()
        {
            if (string.IsNullOrEmpty(IssueDataPath))
            {
                Logger.LogWarning("Issue Folder does not exist");
            }

            var screenshotSuccess = false;
            if (!PluginAPI.bbx_config_get_use_engine_to_capture_screenshot())
            {
#if UNITY_2021_1_OR_NEWER && !UNITY_2023_1_OR_NEWER
                screenshotSuccess = PrepareUnityScreenshot();
#else
                int errorCode = PluginAPI.bbx_capture_screenshot(IssueDataPath);
                screenshotSuccess = errorCode == 0;
                if (errorCode != 0)
                {
                    Logger.LogError($"Error when taking screenshot with ADT lib!!. Errorcode {errorCode}");
                }
#endif
            }

            if (!screenshotSuccess || PluginAPI.bbx_config_get_use_engine_to_capture_screenshot())
            {
                screenshotSuccess = PrepareUnityScreenshot();
            }

        }
        private HotKey DeserializeInputChord(string SerializedString)
        {
            HotKey hotKey = HotKey.Deserialize(SerializedString);

            if (!hotKey.IsValid())
            {
                Logger.LogError("The issue reporter key is not valid. Please recheck BlackBox.ini configuration!!!");
            }
            return hotKey;
        }

        private bool PrepareUnityScreenshot()
        {
            var size = 512;
            StringBuilder OutDir = new StringBuilder(size);
            PluginAPI.bbx_get_issue_report_directory(IssueDataPath, OutDir, size);
            var screenshotSuccess = TakeStandardScreenshotWithUnity(OutDir.ToString());
            PluginAPI.bbx_launch_issue_reporter(IssueDataPath);
            return screenshotSuccess;
        }

        private bool TakeStandardScreenshotWithUnity(string IssueFolder)
        {
            Logger.Log("Capture screenshot via Unity");
            if (!Directory.Exists(IssueFolder))
            {
                Directory.CreateDirectory(IssueFolder);
            }

            var fileName = "image-" + System.DateTime.Now.ToString("yyyyMMddTHHmmssZ") + ".png";
            ScreenCapture.CaptureScreenshot(System.IO.Path.Combine(IssueFolder, fileName));
            return true;
        }
    }
}
#endif