using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.Json;
using RynthCore.Plugin.RynthDefective.Items;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective.Use;
///
/// The controller's view of the game through the engine host. Plugin pump thread only (the
/// plugin's tick), which is also where RynthAi's interfaces may be called.
///
internal sealed unsafe class HostDefWorld : IDefWorld
{
private const long SnapshotMaxAgeMs = 250;
private readonly RynthCoreHost _host;
private readonly HostInventory _reader = new();
private List _items = new();
private long _itemsAtMs = long.MinValue / 4;
private int _revision;
public HostDefWorld(RynthCoreHost host) => _host = host;
public long NowMs => Environment.TickCount64;
public bool InWorld => _host.HasGetPlayerId && _host.GetPlayerId() != 0 && !(_host.HasIsPortaling && _host.IsPortaling());
public uint PlayerId => _host.HasGetPlayerId ? _host.GetPlayerId() : 0;
public uint SelectedId => _host.HasGetSelectedItemId ? _host.GetSelectedItemId() : 0;
public bool ClientBusy => _host.HasGetBusyState && _host.GetBusyState() != 0;
public bool Animating => _host.HasGetCastBusyState && _host.GetCastBusyState() != 0;
public int UseDoneSeq => _host.HasUseDoneSeq ? _host.GetUseDoneSeq() : 0;
public int CombatMode => _host.GetCurrentCombatMode();
public bool? BotWaitingOnServer => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.ServerAction) != 0 : null;
public bool? BotMacroRunning => BotActivity.Read(_host) is { } a ? (a & RynthAiActivity.MacroRunning) != 0 : null;
public int RefusalSeq => _host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out int seq, out _, out _, out _) ? seq : 0;
public bool RefusalNamed(uint objectId) =>
_host.HasGetLastWeenieError && _host.TryGetLastWeenieError(out _, out _, out _, out uint obj) && obj == objectId;
/// The inventory, re-read when it is older than a quarter second.
public IReadOnlyList Items() => Snapshot(SnapshotMaxAgeMs);
/// The inventory, re-read when it is older than .
public List Snapshot(long maxAgeMs)
{
long now = NowMs;
if (now - _itemsAtMs >= maxAgeMs)
{
_items = _reader.Read(_host, now);
_itemsAtMs = now;
_revision++;
}
return _items;
}
/// Counts re-reads (the plugin redraws and re-binds slots when it moved).
public int Revision => _revision;
public CarriedItem? Live(uint id) => _reader.ReadOne(_host, id, NowMs);
public bool UseObject(uint id) => _host.HasUseObject && _host.UseObject(id);
public bool UseObjectOn(uint id, uint target) => _host.HasUseObjectOn && _host.UseObjectOn(id, target);
public bool SetCombatMode(int mode) => _host.HasChangeCombatMode && _host.ChangeCombatMode(mode);
public void Reset()
{
_reader.Reset();
_items = new List();
_itemsAtMs = long.MinValue / 4;
}
}
///
/// RynthAi's activity bits: its "RynthAi.Activity" interface; on an older RynthAi without it, the
/// macro bit from "RynthAi.Status"; null when RynthAi isn't loaded or not ready. Resolved again every
/// call: a RynthAi reload frees the tables. Read only: nothing here changes what RynthAi does.
///
internal static unsafe class BotActivity
{
public static RynthAiActivity? Read(RynthCoreHost host)
{
if (!host.HasGetPluginInterface) return null;
try
{
var act = (RynthAiActivityApiV1*)host.GetPluginInterface("RynthAi", RynthAiActivityApiV1.InterfaceName, RynthAiActivityApiV1.InterfaceVersion);
if (act != null && act->Version >= 1 && act->StructSize >= (uint)sizeof(RynthAiActivityApiV1) && act->GetActivityFlags != null)
{
uint flags = 0;
return act->GetActivityFlags(&flags) != 0 ? (RynthAiActivity)flags : null;
}
var status = (RynthAiStatusApiV1*)host.GetPluginInterface("RynthAi", RynthAiStatusApiV1.InterfaceName, RynthAiStatusApiV1.InterfaceVersion);
if (status != null && status->Version >= 1 && status->StructSize >= (uint)sizeof(RynthAiStatusApiV1) && status->GetStatusJson != null)
{
byte* r = null;
if (status->GetStatusJson(&r) != 0 && r != null)
return FromStatusJson(Marshal.PtrToStringUTF8((IntPtr)r));
}
}
catch
{
// A RynthAi mid-reload: treat as not there this tick.
}
return null;
}
/// The macro bit an older RynthAi's status JSON ({macro, action, ...}) gives (no server-wait bit).
internal static RynthAiActivity? FromStatusJson(string? json)
{
if (string.IsNullOrEmpty(json) || json[0] != '{') return null;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
bool macro = doc.RootElement.TryGetProperty("macro", out JsonElement m) && m.ValueKind == JsonValueKind.True;
return macro ? RynthAiActivity.MacroRunning : RynthAiActivity.None;
}
catch (JsonException)
{
return null;
}
}
}