#include "adapters/eft/aimbot/EftAimbotGateway.h"

#include "adapters/eft/aimbot/AimbotDiagnostics.h"
#include "adapters/eft/aimbot/AimbotTargetScanner.h"
#include "adapters/eft/aimbot/AimbotTargetState.h"
#include "application/messaging/PresentationState.h"

namespace ta::adapters::eft::aimbot
{
EftAimbotGateway::EftAimbotGateway(ta::adapters::eft::runtime::EftGameContext& context)
    : context_(context)
{
    ta::adapters::eft::aimbot::diag::info_once("module_ctor", "Gateway constructed");
}

void EftAimbotGateway::application_tick(const ta::features::aimbot::AimbotSettings& settings)
{
    if (!settings.magic_bullet)
        ta::adapters::eft::aimbot::TargetStateStore::instance().clear_target();
}

void EftAimbotGateway::gameworld_update(
    const ta::adapters::eft::runtime::EftGameContextSnapshot& context,
    const ta::features::aimbot::AimbotSettings& settings)
{

    ta::adapters::eft::aimbot::diag::info_every("gameworld_update", 300, "gameworld_update reached");

    if (!settings.magic_bullet)
    {
        ta::adapters::eft::aimbot::diag::info_every("magic_disabled", 300, "Magic Bullet disabled; clearing target");
        ta::adapters::eft::aimbot::TargetStateStore::instance().set_local_nickname(ta::adapters::eft::aimbot::TargetScanner::read_nickname(context.main_player));
        ta::adapters::eft::aimbot::TargetStateStore::instance().clear_target();
        return;
    }

    const ta::adapters::unity::vector3 screen_center = {ta::application::presentation_state::viewport.acquire().metrics.width / 2,
                                         ta::application::presentation_state::viewport.acquire().metrics.height / 2,
                                         0};
    const ta::adapters::eft::aimbot::ScanResult scan_result = ta::adapters::eft::aimbot::TargetScanner::scan_target(
        context.game_world_instance, context.main_player, screen_center);
    ta::adapters::eft::aimbot::TargetStateStore::instance().set_local_nickname(scan_result.local_nickname);

    if (scan_result.has_target)
    {
        ta::adapters::eft::aimbot::diag::info_every("target_found", 120, "Target acquired");
        ta::adapters::eft::aimbot::TargetStateStore::instance().set_target(scan_result.target);
    }
    else
    {
        ta::adapters::eft::aimbot::diag::info_every("target_missing", 120, "No target found");
        ta::adapters::eft::aimbot::TargetStateStore::instance().clear_target();
    }
}


void EftAimbotGateway::game_tick(const ta::features::aimbot::AimbotSettings& settings)
{
    const auto context = context_.snapshot();
    gameworld_update(context, settings);
}

void EftAimbotGateway::reset_session() noexcept
{
    ta::adapters::eft::aimbot::TargetStateStore::instance().clear_target();
}
}
