#include <cpctelera.h>
#include <stdio.h>
#include <string.h>
#include "main.h"
#include "functions.h"
#include "graphics.h"
#include "texts_eng.h"

void redibujarTile(u8 x, u8 y, u8 ancho, u8 alto) {
	if (x % 2){ //Si estamos en posición impar hay que restablecer todo el tile
		x--;
		ancho++;
	}
	if (ancho % 2){
		ancho = (ancho / 2) + 1;
	} else {
		ancho = (ancho / 2);
	}
	cpct_etm_drawTileBox2x4 (x/2, y/4,ancho, alto/4, 34, CPCT_VMEM_START, &current_map[0] );
}

void renderWeek(){
	u8 i;

	cpct_drawSprite (&G_week[0],  cpctm_screenPtr (CPCT_VMEM_START, 70, 0),10, 8);
	for (i = 0; i < day; i++) {
		cpct_drawSprite (&G_day[0] ,  cpct_getScreenPtr (CPCT_VMEM_START, 70 + (i*2), 0),2, 8);
	}
}

void renderClock(){
	cpct_drawSprite (&G_clock[0],  cpctm_screenPtr (CPCT_VMEM_START, 70, 16),10, 40);

	if (screen == 15)
		cpct_drawSprite (&G_clock[0],  cpctm_screenPtr (CPCT_VMEM_START, 29, 44),10, 40);
}

void renderHour(){
	u8 mod;

	if (hour > 18) 
		mod = hour - 19;
	else
		mod = hour - 7;

	cpct_drawSprite (&G_hour07[0] + (27*mod),  cpctm_screenPtr (CPCT_VMEM_START, 74, 32),3, 9);

	if (screen == 15)
		cpct_drawSprite (&G_hour07[0] + (27*mod),  cpctm_screenPtr (CPCT_VMEM_START, 33, 60),3, 9);
}

void renderEnergy(){
	u8  bar;
	cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 70, 64), cpct_px2byteM0 (4, 4), 5, 8);
	cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 75, 64), cpct_px2byteM0 (13, 13), 4, 8);
	cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 79, 64), 0, 1, 8);

	bar = energy /27;
	cpct_drawSolidBox (cpct_getScreenPtr (CPCT_VMEM_START, 70+bar, 64), cpct_px2byteM0 (1, 1), 1, 8);
}

void renderFace(u8 value) {
	cpct_drawSprite (faces + (150*value),  cpctm_screenPtr (CPCT_VMEM_START, 72, 80),5, 30);			
}

void renderItem(){
	cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 73, 132), cpct_px2byteM0 (0, 0), 5, 20);
	if (object) {
		cpct_drawSprite (&G_o_carKeys[0] + (100*(object-1)),  cpctm_screenPtr (CPCT_VMEM_START, 73, 132),5, 20);			
	}

}

void renderDelete(){
	u8 i,x,y,ancho,alto;
	u8 temp;

	if (screen == 5) { //Borrar teléfonos
		cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 18, 44), cpct_px2byteM0 (14, 14), 2, 4);
      	cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 50, 44), cpct_px2byteM0 (14, 14), 2, 4);
      	cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 26, 92), cpct_px2byteM0 (14, 14), 2, 4);
	}

	//borrado entities
	for (i=0; i < MAX_ENTITIES; i++) {
		if (entities[i].id) {
			ancho = entities[i].width;
			alto = entities[i].height;				
			x = entities[i].x0;
			y = entities[i].y0;
			if (entities[i].id >= 250) { //los elementos de la carretera se borran de otra manera, pues no hay manera de recuperar el Tile original
				cpct_drawSolidBox (cpct_getScreenPtr (CPCT_VMEM_START, entities[i].x0, entities[i].y), 0, ancho, alto);
				if (entities[i].x == 0 || entities[i].x + ancho == 79) {
					// 50% de probabilidades de girar el sprite
					if (cpct_rand() % 2) {
						cpct_hflipSpriteM0 (entities[i].width, entities[i].height,  &entities[i].sprite_f1[0]);
						temp = 1 << ((entities[i].id) - 250); //2^i				
						vehicles = vehicles ^ temp; // marcar el bit correspondiente al inverso
					}
					entities[i].id = 0;
				}
			}
			else {
				redibujarTile(x, y, ancho, alto);	
			}

			// Si ya se cogieron todas las gotas, eliminarla tras borrar
			if (dropsCollected == 10 && entities[i].id == 11) {
					entities[i].id = 0;
					showMessage(ID_SPECIAL_MSG+14);
				}

			//Si ya se ahuyentaron todas las arañas
			if (spiders >= 3 && entities[i].id == 242) {
				activities[19]++;
				entities[i].id = 0;
				showMessage(ID_SPECIAL_MSG+14);
			}

			
		}
	}

	//Quitar basura
	if (screen == 18 && entities[2].id && activities[3] ) {
		entities[2].id = 0;
	}

}


void renderSprites(){
	u8 i;
	u8* sprite;

	u8 start, end;
	i8 next;
	u8 frame_char;

	//Teléfonos
	if (screen == 5 && telephone) {
		cpct_drawSprite (&G_telephone[0],  cpct_getScreenPtr (CPCT_VMEM_START, 2*(telephone % 34), 4*(telephone/34)),2, 4);		
	}

	//Tesoro en Castillo
	if (screen == 8 && activities[ID_DIARY+2] == 0) {
		if (day == 1)
   			cpct_drawSprite (&G_treasure[0],  cpct_getScreenPtr (CPCT_VMEM_START, 16, 72), 4, 8);
   		if (day == 2)
   			cpct_drawSprite (&G_treasure[0],  cpct_getScreenPtr (CPCT_VMEM_START, 44, 88), 4, 8);
   		if (day == 4)
   			cpct_drawSprite (&G_treasure[0],  cpct_getScreenPtr (CPCT_VMEM_START, 48, 28), 4, 8);
   		if (day == 5)
   			cpct_drawSprite (&G_treasure[0],  cpct_getScreenPtr (CPCT_VMEM_START, 42, 60), 4, 8);
   	}


   	// Pintada en la pared
   	if (screen == 10 && activities[35]) {
   		if (extra_char == 1)	
   			cpct_drawSprite (&G_zx[0],  cpct_getScreenPtr (CPCT_VMEM_START, 1, 132), 3, 16);
   		else
   			cpct_drawSprite (&G_cpc[0], cpct_getScreenPtr (CPCT_VMEM_START, 1, 132), 3, 16);
   	}


   	if (screen == 19) {
   		//Borrar cubo de agua
   		if (object == 9)
   			cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 14, 136),  cpct_px2byteM0 (3, 3), 2, 4);

   		//Chorro de agua
   		cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 45, 84),  cpct_px2byteM0 (1, 1), 1, 56);
   		if (hose) {
   			hose--;
   		
	   		if (hose > HOSE_MAX-20) {
	   			cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 45, 84),  cpct_px2byteM0 (9, 9), 1, 56);	
	   		} else {
	   			if (hose % 2)
	   		 		cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 45, 132),  cpct_px2byteM0 (9, 9), 1, 8);	
	   		 	else
	   		 		cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 45, 136),  cpct_px2byteM0 (9, 9), 1, 4);	
	   		}	
	   	}
   	}

   	if (carScreen == screen) {
   		cpct_drawSpriteMasked (G_car_Roland, cpctm_screenPtr (CPCT_VMEM_START, 18, 140), 9, 12);
   	}


	// pintado de entidades, primero al protagonista porque es el que puede subir más arriba en los escenarios y debe ser volcado 
	// a la memoria de vídeo con más prioridad
   	start = 0;
   	end = MAX_ENTITIES;
	next = 1;
	if (screen == 1 || screen == 15 || screen == 10 || screen == 19) { // En la estación cambiar el orden para que el mendigo quede detrás del protagonista
		start = MAX_ENTITIES-1;
   		end = 255;
		next = -1;
	}
	for (i = start; i != end; i = i + next) { 
		if (entities[i].id) {
			//Esto debería hacerse en la función iA, pero se hace aquí para no tener que
			//programar un comportamiento distinto de borrado por cambiar de dimensiones
			if (entities[i].id == 10 && entities[i].data1 == 0) {
				if((u16) entities[i].sprite_f1 == (u16) G_fire_f1) {
					entities[i].y = 136;
					entities[i].height = 16;
					entities[i].sprite_f1 = (u8*) &G_fire_f2[0]; 
					entities[i].sprite_f2 = (u8*) &G_fire_f2[0]; 
					entities[i].sprite_f3 = (u8*) &G_fire_f2[0];
				} else {
					entities[i].y = 144;
					entities[i].height = 8;
					entities[i].sprite_f1 = (u8*) &G_fire_f1[0]; 
					entities[i].sprite_f2 = (u8*) &G_fire_f1[0]; 
					entities[i].sprite_f3 = (u8*) &G_fire_f1[0];
				}
				entities[i].data1 = 10 + (cpct_rand() % 10);
			}

			sprite = entities[i].sprite_f1;
			if (frame > 6) {  //Cada 7 pasos se cambia el sprite
				sprite = entities[i].sprite_f2;
			}
			if (frame > 13) {  //Cada 7 pasos se cambia el sprite
				sprite = entities[i].sprite_f3;
			}
			if (frame > 20) {  //Cada 7 pasos se cambia el sprite
				sprite = entities[i].sprite_f2;
			}

			if (i == 0) { //Animación especial para el protagonista cada 3 frames cambia y vuelve a f1
				frame_char = frame % 9;
				sprite = entities[i].sprite_f1;
				if (frame_char > 2) {  
					sprite = entities[i].sprite_f2;
				}
				if (frame_char > 5) {  
					sprite = entities[i].sprite_f3;
				}
			}

			if (entities[i].id < 240) 
				cpct_drawSpriteMasked (sprite, cpct_getScreenPtr (CPCT_VMEM_START, entities[i].x, entities[i].y), entities[i].width, entities[i].height);
			else
				cpct_drawSprite (sprite, cpct_getScreenPtr (CPCT_VMEM_START, entities[i].x, entities[i].y), entities[i].width, entities[i].height);

			entities[i].x0 = entities[i].x;
			entities[i].y0 = entities[i].y;
			
		}
	}
	frame++;

	if (frame == 28)
		frame = 0;

}


void renderText(){
	if (possibleActivity < ID_SPECIAL_MSG && textPrinted != 1) { // No volver a pintar, si el texto pintado en el frame anterior fue de este tipo (1, textos normales)
		mydrawStringM1(txt_act, cpctm_screenPtr(CPCT_VMEM_START, 0, 192));
		mydrawStringM1(&txt_act0_0[0] + (possibleActivity*16), cpctm_screenPtr(CPCT_VMEM_START, 28, 192));
		//Borrar posible texto-consejo anterior
		cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 58, 192), 0, 20, 8);

		textPrinted = 1;
	}
	
	if (possibleActivity == 255) {
		if (hintText != 0 && hintTextTime ) {
			if (!textPrinted) {
				mydrawStringM1(&txt_special_00[0] + ((hintText-ID_SPECIAL_MSG)*40), cpctm_screenPtr(CPCT_VMEM_START, 0, 192));
				textPrinted = 2; //Para que no se vuelva a pintar, pero para que tampoco se borre
			}

			hintTextTime--;
			if (!hintTextTime) { //se acabó el tiempo que tenía que estar en pantalla, marcar para borrado
				//Para el mensaje inicial, comportamiento diferente para mostrar una secuencia
				/*if (hintText >= ID_SPECIAL_MSG+1 && hintText <= ID_SPECIAL_MSG+3) {
					hintText++; 
					hintTextTime = HINT_TIME_ON_SCREEN+1;
					textPrinted = 0;
				} else {*/
					hintText = 0;
					textPrinted = 1;
					possibleActivity = 255;
				//}
			}
		} 
		if (textPrinted == 1) { // No hay actividad. Borrar posible texto anterior
			cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START, 0, 192), 0, 64, 8);
			cpct_drawSolidBox (cpctm_screenPtr (CPCT_VMEM_START,64, 192), 0, 16, 8);
			textPrinted = 0;
		}
	}
}

void render(){
//cpct_setBorder(HW_RED);		
		renderDelete(); //Pintado-Borrar
//cpct_setBorder(HW_BRIGHT_MAGENTA);
	    renderSprites(); //Pintado-Pintar

	    if (reset_face > 0){
	    	reset_face--;
	    	if (!reset_face)
	    		renderFace(0);
	    }
//cpct_setBorder(HW_BLUE);
//		renderText();
//cpct_setBorder(HW_BLACK);		
}


void renderScore(u8 score){
	u8 txt_score[5];

	txt_score[0] = 43;
	if (score < 127) {
		txt_score[0] = 45; 
	}

	txt_score[1] = 48 + (abs(score - 127)) / 100; //48 es el carácter para 0
	txt_score[2] = 48 + (abs(score - 127) % 100) / 10;
	txt_score[3] = 48 + (abs(score - 127)) % 10;
	txt_score[4] = 0;
	mydrawStringM1(txt_score, cpctm_screenPtr(CPCT_VMEM_START, 23, 192));

}

void renderScoreboard() {
	renderWeek();
	renderClock();
	renderHour();
	renderEnergy();
	renderFace(0);
	

	cpct_drawSprite (&G_item[0], cpctm_screenPtr (CPCT_VMEM_START, 72, 120), 8, 8);

	renderItem();
	
}

