#include <cpctelera.h>
#include "main.h"
#include "functions.h"
#include "graphics.h"
#include "calendar.h"
#include "game.h"
#include "render.h"
#include "m_menu.h"

void menu() {
	u8 seed, start;
	u16 delay;
	i8 mode;

	cpct_akp_musicInit((u8*) m_menu);
	music_playing = 1;	
    
    clearScreens();
    *(u8*)&paletteM0[3] = HW_PASTEL_CYAN;
    updatePalette();

    start = 0;
    delay = 65535;

    spriteset = (u8*) &G_sprite_f1[0];
	faces = (u8*) &G_face0[0];
	extra_char = 0;
    
    while (!start) {
	    screen = cpct_rand() % 21; 
	    mode = 2;
	    while (mode == 2) { 
	    	mode = cpct_rand() % 5;
	    }
	    mode = mode - 2; // Para que mode tenga valores -2, -1, 1 y 2
	    waitBorder();
	    initScreen(mode);

	    //El sprite del calendario está comprimido, se descomprime en el buffer para los tiles pues en este momento no es necesario.
	    //Pues no habrán borrados de sprites y por tanto, no se tiene que restaurar el escenario.
	    cpct_zx7b_decrunch_s((void *) (&current_map[0] + calendar_size - 1),(u8 *) calendar_end);
	    cpct_drawSprite (&current_map[0],  cpctm_screenPtr (CPCT_VMEM_START, 21, 148),27, 36);
	    cpct_drawSpriteMasked (&G_sprite_f1[0], cpctm_screenPtr (CPCT_VMEM_START, 44, 171), 3, 16);

		mydrawStringM1(txt_highscore, cpctm_screenPtr(CPCT_VMEM_START, 0, 192));
		renderScore(hiscore);

		delay = 65535;
		while (delay) {
			
			if (cpct_isAnyKeyPressed_f()) {
				start = 1;
				break;
			}

			if (delay == 65535) 
				mydrawStringM1(txt_pressKey, cpctm_screenPtr(CPCT_VMEM_START, 36, 192));
			if (delay == 52428)
				mydrawStringM1(txt_credits1, cpctm_screenPtr(CPCT_VMEM_START, 36, 192));
			if (delay == 39321)
				mydrawStringM1(txt_credits2, cpctm_screenPtr(CPCT_VMEM_START, 36, 192)); 
			if (delay == 26214)
				mydrawStringM1(txt_credits3, cpctm_screenPtr(CPCT_VMEM_START, 36, 192)); 
			if (delay == 13107)
				mydrawStringM1(txt_credits4, cpctm_screenPtr(CPCT_VMEM_START, 36, 192));
			delay--;
		}
	}

	seed = (u8) delay;
	cpct_srand8(seed);

	for (delay = 0; delay < 1024; delay++) {
		if (cpct_isKeyPressed(Key_Z) && cpct_isKeyPressed(Key_X)) {
			cpct_setBorder( paletteM0 [((u8) delay % 16)]);
			spriteset = (u8*) &G_sprite_f1_COPY[0];
			faces = (u8*) &G_face0_COPY[0];
			extra_char = 1;
		}
	}
	cpct_setBorder(HW_BLACK);
	

	
	music_playing = 0;
	cpct_akp_stop ();
    fade();
}