/* PlayAgain's wireless core: one mGBA Game Boy Advance core with a Wireless
 * Adapter on its link port (rfu.c, ported from gpSP). Because rfu.c is
 * GPL-2.0-or-later, this whole wasm is GPL-2.0-or-later as distributed; its
 * complete source is beside it.
 *
 * Each home runs its own core at its own pace. The adapter's outgoing
 * packets wait in a queue the page drains after each frame
 * (mw_take_packet); packets from the other home are pushed in before the
 * next frame (mw_push_packet) — Pokémon does all its adapter traffic in one
 * burst after VBlank, so between frames is enough.
 */
#include <mgba/core/core.h>
#include <mgba/core/config.h>
#include <mgba/core/log.h>
#include <mgba/internal/gba/gba.h>
#include <mgba/internal/gba/savedata.h>
#include <mgba/internal/gba/sio.h>
#include <mgba-util/audio-buffer.h>
#include <mgba-util/audio-resampler.h>
#include <mgba-util/vfs.h>

#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#define VW 256
#define VH 224
#define SCREEN_W 240
#define SCREEN_H 160
#define AUDIO_RATE 48000
#define AUDIO_FRAMES 0x4000
#define OUT_PACKETS 256
#define OUT_BYTES 128

/* rfu.c */
struct GBASIODriver* rfu_driver_create(void);
void rfu_frame_update(void);
void rfu_net_receive(const void* buf, size_t len, uint16_t client_id);
void rfu_peer_gone(void);
uint32_t rfu_get(int what);
extern int rfu_qdepth, rfu_client_ttl_frames;
struct RFUStats {
	uint32_t txPkts[8], txBytes;
	uint32_t rxPkts[8], rxBytes;
	uint32_t dropHostQ, dropClientQ, malformed, badLen;
	uint32_t respData, respNoData, respTimeout, respDisc;
	uint32_t cmdCount[64];
	uint32_t unknownCmds;
	uint32_t maxQHost, maxQClient;
	uint32_t resets;
};
extern struct RFUStats rfu_stats;

uint32_t rfu_salt = 0;

static struct mCore* core;
static mColor* video;
static void* rom;
static uint32_t frame[SCREEN_W * SCREEN_H];
static struct mAudioBuffer out;
static struct mAudioResampler resampler;
static double sourceRate;

/* Outgoing adapter packets, oldest first. */
static struct {
	uint16_t to;
	uint16_t len;
	uint8_t bytes[OUT_BYTES];
} outbox[OUT_PACKETS];
static unsigned outHead, outCount, outOverflow;
static uint16_t lastTo;

static void _log(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
	(void) logger;
	(void) category;
	(void) level;
	(void) format;
	(void) args;
}
static struct mLogger silent = { .log = _log, .filter = NULL };

/* rfu.c's way out: queued for the page. A packet over OUT_BYTES or a full queue is counted and dropped. */
void rfu_host_send(uint16_t to, const void* buf, size_t len) {
	if (len > OUT_BYTES || outCount >= OUT_PACKETS) {
		++outOverflow;
		return;
	}
	unsigned at = (outHead + outCount) % OUT_PACKETS;
	outbox[at].to = to;
	outbox[at].len = (uint16_t) len;
	memcpy(outbox[at].bytes, buf, len);
	++outCount;
}

/* gpSP's mid-wait poll is off (rfu_poll_mid_wait = 0): packets arrive between frames. */
void rfu_host_poll(void) {}

static int _typeForSize(int bytes) {
	switch (bytes) {
	case 512: return GBA_SAVEDATA_EEPROM512;
	case 8192: return GBA_SAVEDATA_EEPROM;
	case 32768: return GBA_SAVEDATA_SRAM;
	case 65536: return GBA_SAVEDATA_FLASH512;
	case 131072: return GBA_SAVEDATA_FLASH1M;
	}
	return -1;
}

void mw_init(void) { mLogSetDefaultLogger(&silent); }

/* The home's cartridge and battery; its clock starts at `epochMs` as the cartridge shows it and moves with
 * emulated frames. `salt` keeps two homes that booted alike from drawing the same adapter ids.
 * 1 on success, 0 on failure, -2 when the battery was not taken whole. */
int mw_load(const void* romData, int romBytes, const void* battery, int batteryBytes, double epochMs, int salt) {
	if (core) return 0;
	rom = malloc(romBytes);
	memcpy(rom, romData, romBytes);
	struct VFile* vf = VFileFromMemory(rom, romBytes);
	core = mCoreCreate(mPLATFORM_GBA);
	if (!core) return 0;
	mCoreInitConfig(core, NULL);
	if (!core->init(core)) return 0;
	struct mCoreOptions defaults = { .useBios = true, .skipBios = false, .volume = 0x100, .logLevel = 0 };
	mCoreConfigLoadDefaults(&core->config, &defaults);
	mCoreLoadConfig(core);
	video = calloc(VW * VH, sizeof(mColor));
	core->setVideoBuffer(core, video, VW);
	core->setAudioBufferSize(core, AUDIO_FRAMES);
	if (!core->loadROM(core, vf)) return 0;
	core->reset(core);
	struct GBA* gba = core->board;
	if (battery && batteryBytes > 0) {
		if (gba->memory.savedata.type == GBA_SAVEDATA_AUTODETECT) {
			int type = _typeForSize(batteryBytes);
			if (type < 0) return -2;
			GBASavedataForceType(&gba->memory.savedata, (enum GBASavedataType) type);
		}
		if (!core->savedataRestore(core, battery, batteryBytes, true)) return -2;
		if ((int) GBASavedataSize(&gba->memory.savedata) != batteryBytes) return -2;
	}
	core->rtc.override = RTC_FAKE_EPOCH;
	core->rtc.value = (int64_t) epochMs;
	rfu_salt = (uint32_t) salt;
	mAudioBufferInit(&out, AUDIO_FRAMES, 2);
	mAudioResamplerInit(&resampler, mINTERPOLATOR_SINC);
	sourceRate = 0;
	return 1;
}

/* Plugs the Wireless Adapter into the link port. */
void mw_attach_adapter(void) { core->setPeripheral(core, mPERIPH_GBA_LINK_PORT, rfu_driver_create()); }

void mw_set_keys(unsigned keys) { core->setKeys(core, keys); }

uint32_t mw_run_frame(void) {
	core->runFrame(core);
	rfu_frame_update();
	return core->frameCounter(core);
}

void mw_push_packet(const uint8_t* bytes, int len, int from) {
	if (len < 0) return;
	rfu_net_receive(bytes, (size_t) len, (uint16_t) from);
}

/* Copies the oldest outgoing packet to `dst` (at most `max` bytes); its length, or 0 when there is none. */
int mw_take_packet(uint8_t* dst, int max) {
	if (!outCount) return 0;
	unsigned at = outHead;
	int len = outbox[at].len;
	if (len > max) return -1;
	memcpy(dst, outbox[at].bytes, len);
	lastTo = outbox[at].to;
	outHead = (outHead + 1) % OUT_PACKETS;
	--outCount;
	return len;
}

/* Where the packet mw_take_packet just gave goes: a client id, or 0xFFFF for everyone. */
int mw_last_to(void) { return lastTo; }

/* The other home left or the channel dropped: the game sees its partner go. */
void mw_disconnect(void) { rfu_peer_gone(); }

/* 1: queue depth (1..64); 3: frames a host holds a silent client. */
void mw_config(int what, int value) {
	if (what == 1) rfu_qdepth = value < 1 ? 1 : value > 64 ? 64 : value;
	if (what == 3) rfu_client_ttl_frames = value < 1 ? 1 : value;
}

/* 0 packets dropped on full queues; 1 malformed or bad-length packets; 2/3 deepest host/client queue;
 * 4 packets sent; 5 packets received; 6 outgoing packets dropped here; 7 the adapter's state. */
uint32_t mw_stats(int which) {
	uint32_t sum = 0;
	switch (which) {
	case 0: return rfu_stats.dropHostQ + rfu_stats.dropClientQ;
	case 1: return rfu_stats.malformed + rfu_stats.badLen;
	case 2: return rfu_stats.maxQHost;
	case 3: return rfu_stats.maxQClient;
	case 4:
		for (int i = 0; i < 8; ++i) sum += rfu_stats.txPkts[i];
		return sum;
	case 5:
		for (int i = 0; i < 8; ++i) sum += rfu_stats.rxPkts[i];
		return sum;
	case 6: return outOverflow;
	case 7: return rfu_get(1);
	}
	return 0;
}

/* RGBA8888, 240 × 160, alpha forced. */
uint32_t* mw_framebuffer(void) {
	for (int y = 0; y < SCREEN_H; ++y) {
		for (int x = 0; x < SCREEN_W; ++x) frame[y * SCREEN_W + x] = (uint32_t) video[y * VW + x] | 0xFF000000u;
	}
	return frame;
}

int mw_read_audio(int16_t* dst, int maxFrames) {
	double rate = core->audioSampleRate(core);
	if (rate != sourceRate) {
		mAudioResamplerSetSource(&resampler, core->getAudioBuffer(core), rate, true);
		mAudioResamplerSetDestination(&resampler, &out, AUDIO_RATE);
		sourceRate = rate;
	}
	mAudioResamplerProcess(&resampler);
	return (int) mAudioBufferRead(&out, dst, maxFrames);
}

int mw_battery_size(void) { return (int) GBASavedataSize(&((struct GBA*) core->board)->memory.savedata); }

/* 0 on success. */
int mw_save_battery(uint8_t* dst) {
	struct GBASavedata* savedata = &((struct GBA*) core->board)->memory.savedata;
	size_t n = GBASavedataSize(savedata);
	if (n && !savedata->data) return -1;
	if (n) memcpy(dst, savedata->data, n);
	return 0;
}

double mw_frame_rate(void) { return (double) core->frequency(core) / core->frameCycles(core); }

/* Tests: work RAM, region 0 EWRAM (256 KiB), 1 IWRAM (32 KiB). */
uint8_t* mw_debug_memory(int region) {
	struct GBA* gba = core->board;
	return (uint8_t*) (region ? gba->memory.iwram : gba->memory.wram);
}
