#include "../data.h"
#include "../game.h"
#include "mario.h"

void vg_object_mario_logic(VG_SPRITE * sp)
{
	int i;
	
	if(vg_level->tilemap->r == 1)
	{
		if(sp->d1 > 0)
		{
			sp->d1--;
		}
		sp->timer++;
		sp->frame++;
		if(sp->timer % 55 == 0)
		{
			vg_create_projectile(vg_animation[VG_ANIMATION_MSHOT], VG_PROJECTILE_MARIO_SHOT, sp->x, sp->y + itofix(12), itofix(-4), itofix(0));
			ncds_play_sample(vg_sound[VG_SOUND_PLAYER_SHOOT], 127, -1, -1);
		}
		switch(sp->state)
		{
			case 0:
			{
				sp->x -= itofix(1);
				update_collision_map(&sp->cmap[sp->state], fixtoi(sp->x), fixtoi(sp->y));
				if(sp->timer % 50 == 0)
				{
					sp->state = 2;
					ncds_play_sample(vg_sound[VG_SOUND_PLAYER_JUMP], 127, -1, -1);
					sp->vy = itofix(-7);
				}
				break;
			}
			case 2:
			{
				sp->x += itofix(1);
				sp->y += sp->vy;
				sp->vy += ftofix(VG_CHARACTER_GRAVITY);
				update_collision_map(&sp->cmap[sp->state], fixtoi(sp->x), fixtoi(sp->y));
				if(tilemap_collide(vg_level->tilemap, &sp->cmap[sp->state]))
				{
					sp->y = itofix(get_sprite_y(&sp->cmap[sp->state], 16));
					update_collision_map(&sp->cmap[sp->state], fixtoi(sp->x), fixtoi(sp->y));
					sp->vy = itofix(0);
				}
				if(sp->timer % 50 == 0)
				{
					sp->state = 0;
				}
				break;
			}
		}
	}
}

void vg_object_mario_hit(VG_SPRITE * sp)
{
	if(vg_player.sprite.state != VG_CHARACTER_HIT_LEFT && vg_player.sprite.state != VG_CHARACTER_HIT_RIGHT)
	{
		if(fixtoi(vg_player.sprite.x) + vg_player.sprite.cmap[0].rx + vg_player.sprite.cmap[0].top.point[0].x < fixtoi(sp->x) + sp->cmap[0].rx + sp->cmap[0].top.point[0].x)
		{
			vg_player_set_state(VG_CHARACTER_HIT_RIGHT);
			vg_player.sprite.vx = itofix(-5);
			vg_player.sprite.timer = 0;
			if(vg_character_take_hit(&vg_player, 50))
			{
				ncds_play_sample(vg_sound[VG_SOUND_PLAYER_DIE], 127, -1, -1);
				if(vg_player.lives > 0)
				{
					vg_game_restart_level();
				}
				else
				{
					ncds_stop_music();
					fade_out(4);
					vg_state = VG_STATE_TITLE;
					vg_logic();
					vg_update();
					vg_draw();
					fade_in(vg_palette, 4);
					ncds_play_music("title.xm", 1);
					gametime_reset();
				}
			}
		}
		else
		{
			vg_player_set_state(VG_CHARACTER_HIT_LEFT);
			vg_player.sprite.vx = itofix(5);
			vg_player.sprite.timer = 0;
			if(vg_character_take_hit(&vg_player, 50))
			{
				ncds_play_sample(vg_sound[VG_SOUND_PLAYER_DIE], 127, -1, -1);
				if(vg_player.lives > 0)
				{
					vg_game_restart_level();
				}
				else
				{
					ncds_stop_music();
					fade_out(4);
					vg_state = VG_STATE_TITLE;
					vg_logic();
					vg_update();
					vg_draw();
					fade_in(vg_palette, 4);
					ncds_play_music("title.xm", 1);
					gametime_reset();
				}
			}
		}
	}
}
