/*
 *	Copyright (c) 2024 Scott Duensing, scott@kangaroopunch.com
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *	SOFTWARE.
 */


/*
 * Z-Machine for the Foenix F256 computers.
 *
 * F256 machines are 65c02 based systems with 512k of banked RAM.
 * As such, this ZIP is going to load the story entirely into "high"
 * memory (above the 64k accessable to the CPU) and page things in
 * and out as needed.
 *
 * To keep library code at a minimum, we'll also statically allocate
 * as much as possible and do other "bad" things now frowned upon in
 * modern development.  :-)
 */


#include "f256.h"

#include "portme.h"
#include "story.h"
#include "memory.h"
#include "state.h"
#include "interpreter.h"
#include "../../include/text.h"


#define BASE_ADDRESS   0x10000


static char *_saveName = 0;


void portAttributeSet(byte attribute) {
	switch (attribute) {
		case TEXT_ATTR_NORMAL:
			textSetColor(7, 1);
			break;

		case TEXT_ATTR_REVERSE:
			textSetColor(1, 7);
			break;

		case TEXT_ATTR_BOLD:
			textSetColor(15, 1);
			break;

		case TEXT_ATTR_EMPHASIS:
			textSetColor(14, 1);
			break;
	}
}


uint8_t portByteGet(uint32_t address) {
	return FAR_PEEK(BASE_ADDRESS + address);
}


void portByteSet(uint32_t address, uint8_t value) {
	FAR_POKE(BASE_ADDRESS + address, value);
}


void portCharGetPos(byte *x, byte *y) {
	byte tx;
	byte ty;

	textGetXY(&tx, &ty);
	// ZIP uses 1-based coordinates.
	*x = tx + 1;
	*y = ty + 1;
}


void portCharPrint(char c) {
	static char ch[2] = { 0, 0 };
	ch[0] = c;
	textPrint(ch);
}


void portCharSetPos(byte x, byte y) {
	// ZIP uses 1-based coordinates.
	textGotoXY(x - 1, y - 1);
}


void portDie(char *fmt, ...) {
#ifdef DEBUGGING
	printf("%s\n", fmt);  // Yeah, this isn't right.
#endif
	exit(1);
}


bool portFileRestore(void) {

	FILE     *in;
	bool      ok  = false;
	uint32_t  i;
	byte      b;

	in = fopen(_saveName, "rb");
	if (in) {
		ok = true;

		// Read in PC.
		ok &= (fread(&__state.pc, sizeof(__state.pc), 1, in) == 1);
		// Read in SP.
		ok &= (fread(&__state.sp, sizeof(__state.sp), 1, in) == 1);
		// Read in BP.
		ok &= (fread(&__state.bp, sizeof(__state.bp), 1, in) == 1);
		// Read in dynamic game RAM.
		for (i=0; i<storyStaticMemoryBaseAddress(); i++) {
			ok &= (fread(&b, 1, 1, in) == 1);
			ZPOKE(i, b);
		}
		// Read in stack.
		ok &= (fread(__state.stack, sizeof(__state.stack[0]), __state.sp, in) == __state.sp);

		fclose(in);
	}

	return ok;
}


bool portFileSave(void) {
	FILE     *out;
	bool      ok  = false;
	uint32_t  i;
	byte      b;

	out = fopen(_saveName, "wb");
	if (out) {
		ok = true;

		// Write out PC.
		ok &= (fwrite(&__state.pc, sizeof(__state.pc), 1, out) == 1);
		// Write out SP.
		ok &= (fwrite(&__state.sp, sizeof(__state.sp), 1, out) == 1);
		// Write out BP.
		ok &= (fwrite(&__state.bp, sizeof(__state.bp), 1, out) == 1);
		// Write out dynamic game RAM.
		for (i=0; i<storyStaticMemoryBaseAddress(); i++) {
			b = ZPEEK(i);
			ok &= (fwrite(&b, 1, 1, out) == 1);
		}
		// Write out stack.
		ok &= (fwrite(__state.stack, sizeof(__state.stack[0]), __state.sp, out) == __state.sp);

		fclose(out);
	}

	return ok;
}


char portCharGet(void) {
#if 0
	static char     playback[] = "open mailbox\ntake leaflet\nread leaflet\ndrop leaflet\n";
	static uint32_t pointer = 0;

	if (pointer < libStrLen(playback)) return playback[pointer++];
#endif

	return getchar();
}


uint16_t portRandomGet(int16_t range) {
	// If range is zero, randomize with "best" random seed.
	// If range is negative, use the positive value to seed.

	if (range == 0) return 0;

	if (range < 0) {
		randomSeed(-range);
		return 0;
	}

	return (randomRead() % range) + 1;
}


void portStoryLoad(void) {

	// On the F256, the story is loaded into RAM along with the ZIP.
	// ***TODO*** This likely breaks the "restart" command.

	// Later, we probably want to see if the user has a memory expansion
	// installed.  If they do, we can use it and then use the lower memory
	// for graphics and sound.

	storyChecksumCalculate();
}


uint16_t portWordGet(uint32_t address) {
	return SWAP_UINT16(FAR_PEEKW(BASE_ADDRESS + address));
}


void portWordSet(uint32_t address, uint16_t value) {
	FAR_POKEW(BASE_ADDRESS + address, SWAP_UINT16(value));
}


int main(void) {
	byte c;
	byte colors[16][3] = {
		{ 0x00, 0x00, 0x00 },
		{ 0x00, 0x00, 0xaa },
		{ 0x00, 0xaa, 0x00 },
		{ 0x00, 0xaa, 0xaa },
		{ 0xaa, 0x00, 0x00 },
		{ 0xaa, 0x00, 0xaa },
		{ 0xaa, 0x55, 0x00 },
		{ 0xaa, 0xaa, 0xaa },
		{ 0x55, 0x55, 0x55 },
		{ 0x55, 0x55, 0xff },
		{ 0x55, 0xff, 0x55 },
		{ 0x55, 0xff, 0xff },
		{ 0xff, 0x55, 0x55 },
		{ 0xff, 0x55, 0xff },
		{ 0xff, 0xff, 0x55 },
		{ 0xff, 0xff, 0xff }
	};

	_saveName = "zork1.sav";

	f256Init();

	// Load EGA palette into text CLUT.
	for (c=0; c<16; c++) {
		textDefineForegroundColor(c, colors[c][0], colors[c][1], colors[c][2]);
		textDefineBackgroundColor(c, colors[c][0], colors[c][1], colors[c][2]);
	}
	textEnableBackgroundColors(true);

	textSetColor(15, 0);
	textPrint("Welcome to MUDDLE Beta 1, Another Z-Machine!\n\n");
	textSetColor(7, 0);
	textPrint("Copyright 2024 Scott Duensing, All Rights Reserved.\n");
	textPrint("Kangaroo Punch Studios   https://kangaroopunch.com\n\n\n");
	textSetColor(8, 0);
	textPrint("Thinking...");

	stateReset();
	portStoryLoad();
	opcodesSetup();
	storySetup(80, 30);

	textSetColor(7, 1);
	textClear();
	textSetCursor(199);

	interpreterRun();

	return 0;
}
