/* Menu Thing for RVController - Games
 * A product of Advanced Mesecons Devices, a Cheapie Systems company
 * This is free and unencumbered software released into the public domain.
 * See http://unlicense.org/ for more information */

#include <stdint.h>
#include <stdbool.h>
#include "rvcontroller-ecalls.h"

void runCasino(void) {
	int32_t input;
	int32_t money = 10;
	bool quit = false;
	char strscratch[1];

	printstr("\nCASINO\n");

	while (!quit) {
		printstr("You have:\n$");
		printint(money);
		printstr("\nBet how much?\n(0 to quit)\n> ");
		input = readint();
		printint(input);
		printchar('\n');

		if (input == 0) {
			quit = true;
		} else if (input < 0 || input > money) {
			printstr("Nice try.\n");
		} else {
			if (randomint(0,9) >= 6) { // Of course it's not a fair chance. This is a casino, gotta make money here!
				printstr("You win!\n");
				money = money + input;
				if (money >= 1000000000) {
					printstr("You're a \nbillionaire!\nBest quit while\nyou're ahead...\n\nPress any key");
					readstr(strscratch,1);
					quit = true;
				}
			} else {
				printstr("You lose.\n");
				money = money - input;
				if (money <= 0) {
					printstr("You've gambled away\nyour life savings.\nTime to go home...\n\nPress any key");
					readstr(strscratch,1);
					quit = true;
				}
			}
		}
	}
}

void runGuessNum(void) {
	int32_t answer = randomint(1,99);
	int32_t entry;
	int32_t guesses = 0;
	uint32_t time = rdtime();
	bool quit = false;
	char strscratch[1];

	printstr("GUESS THE NUMBER\nThe computer will\npick a number from\n1 to 99 and you need\nto guess it.\n\nPress any key");
	readstr(strscratch,1);
	printstr("\n\n\n\n");

	while (!quit) {
		printstr("Enter your guess:\n(0 to quit)\n> ");
		entry = readint();
		if (entry == 0) {
			quit = true;
		}
		printint(entry);
		guesses = guesses + 1;

		if (entry == answer) {
			printstr("\nCorrect!\n\nYou got it in:\n");
			printint(guesses);
			printstr(" guess");
			if (guesses != 1) { printstr("es"); }
			printchar('\n');
			time = rdtime() - time;
			printint(time);
			printstr(" second");
			if (time != 1) { printchar('s'); }
			printstr("\nPress any key");
			readstr(strscratch,1);
			quit = true;
		} else if (entry > answer) {
			printstr("\nToo high!\n\n");
		} else {
			printstr("\nToo low!\n\n");
		}
	}
}

void runGames(void) {
	char inputbuf[2];
	bool quit = false;
	while (!quit) {
		printstr("\nGAMES\n");
		printstr("1: Casino\n");
		printstr("2: Guess the Number\n");
		printstr("\n\n0: Back");
		readstr(inputbuf,2);

		switch (inputbuf[0]) {
			case '0':
				quit = true;
				break;
			case '1':
				runCasino();
				quit = true;
				break;
			case '2':
				runGuessNum();
				quit = true;
				break;
			default:
				printstr("\nInvalid option\n\nPress any key\n\n\n");
				readstr(inputbuf,2);
		}
	}
}
