/*
 * Puente entre libatari800 y la pagina "Pruebalo en tu navegador" (landing/js/try.js).
 * Lo compila tools/web/build_emu.sh junto con atari800 (GPL 2 o posterior, como atari800).
 *
 * Copyright (C) 2026 MyComuApp (Valparaiso, Chile). Parte de la compilacion web de atari800.
 * SPDX-License-Identifier: GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
 * version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License (COPYING).
 *
 * La pagina llama: a8_init (maquina), a8_boot (un .atr del sistema de archivos de Emscripten), a8_frame (un cuadro
 * con la entrada) y lee la pantalla (a8_screen, 384x240 indices de color), la paleta (a8_palette, 256 RGB) y el
 * sonido del cuadro (a8_sound, a8_sound_len). Lo que el Atari imprime por P: se suma a /printed.txt (a8_printed
 * cuenta los trabajos): atari800 llama a system("lpr <archivo>") al cerrar P:, y aqui system() copia ese archivo.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <emscripten.h>

#include "config.h"
#include "atari.h"
#include "colours.h"
#include "libatari800.h"

static input_template_t in;
static int printed;

/* reemplaza a system() de la biblioteca de C: el unico que lo llama es el parche P: de atari800, con su comando de
   impresion ("lpr %s" por omision); el archivo es lo ultimo de la linea */
int system(const char *cmd)
{
	const char *path;
	FILE *src, *dst;
	char buf[512];
	size_t n;
	if (cmd == NULL)
		return 1;
	path = strrchr(cmd, ' ');
	path = path ? path + 1 : cmd;
	src = fopen(path, "rb");
	if (src == NULL)
		return -1;
	dst = fopen("/printed.txt", "ab");
	if (dst == NULL) {
		fclose(src);
		return -1;
	}
	while ((n = fread(buf, 1, sizeof buf, src)) > 0)
		fwrite(buf, 1, n, dst);
	fclose(src);
	fclose(dst);
	printed++;
	return 0;
}

EMSCRIPTEN_KEEPALIVE int a8_printed(void) { return printed; }
static char *args[24];

/* pal: 0 NTSC, 1 PAL; basic: 0 apagado (como con OPTION al arrancar), 1 encendido */
EMSCRIPTEN_KEEPALIVE int a8_init(int pal, int basic)
{
	int n = 0;
	args[n++] = "atari800";
	args[n++] = "-xl";
	args[n++] = "-xl-rev";
	args[n++] = "altirra";
	args[n++] = "-basic-rev";
	args[n++] = "altirra";
	args[n++] = basic ? "-basic" : "-nobasic";
	args[n++] = pal ? "-pal" : "-ntsc";
	args[n++] = "-sound";
	args[n++] = "-dsprate";
	args[n++] = "48000";
	args[n++] = "-audio16";
	args[n] = NULL;
	libatari800_clear_input_array(&in);
	return libatari800_init(n, args);
}

/* arranca un disco (ruta en el sistema de archivos de Emscripten): lo monta en D1: y reinicia */
EMSCRIPTEN_KEEPALIVE int a8_boot(const char *path)
{
	return libatari800_reboot_with_file(path);
}

/* un cuadro. keychar: ASCII (letras, cifras, signos); keycode: codigo AKEY del Atari (flechas, HELP...);
   special: AKEY negativo (BREAK, reinicio); consol: bits 1 START, 2 SELECT, 4 OPTION; joy: bits 1 arriba,
   2 abajo, 4 izquierda, 8 derecha; trig: gatillo */
EMSCRIPTEN_KEEPALIVE int a8_frame(int keychar, int keycode, int special, int shift, int control, int consol, int joy,
                                  int trig)
{
	in.keychar = (UBYTE)keychar;
	in.keycode = (UBYTE)keycode;
	in.special = (UBYTE)special;
	in.shift = (UBYTE)shift;
	in.control = (UBYTE)control;
	in.start = (consol & 1) != 0;
	in.select = (consol & 2) != 0;
	in.option = (consol & 4) != 0;
	in.joy0 = (UBYTE)joy;
	in.trig0 = (UBYTE)trig;
	return libatari800_next_frame(&in);
}

EMSCRIPTEN_KEEPALIVE UBYTE *a8_screen(void) { return libatari800_get_screen_ptr(); }
EMSCRIPTEN_KEEPALIVE int *a8_palette(void) { return Colours_table; }
EMSCRIPTEN_KEEPALIVE UBYTE *a8_sound(void) { return libatari800_get_sound_buffer(); }
EMSCRIPTEN_KEEPALIVE int a8_sound_len(void) { return libatari800_get_sound_buffer_len(); }
EMSCRIPTEN_KEEPALIVE int a8_sound_freq(void) { return libatari800_get_sound_frequency(); }
EMSCRIPTEN_KEEPALIVE int a8_sound_bytes(void) { return libatari800_get_sound_sample_size(); }
EMSCRIPTEN_KEEPALIVE int a8_sound_channels(void) { return libatari800_get_num_sound_channels(); }
EMSCRIPTEN_KEEPALIVE UBYTE *a8_memory(void) { return libatari800_get_main_memory_ptr(); }
/* vacia los archivos abiertos: sin esto el ultimo sector grabado seguia en el bufer de C y la copia del disco salia atrasada */
EMSCRIPTEN_KEEPALIVE int a8_sync(void) { return fflush(NULL); }
EMSCRIPTEN_KEEPALIVE float a8_fps(void) { return libatari800_get_fps(); }
