namespace rectangle_battle
{
	enum ORIENTATION
	{
		UP,
		DOWN
	};
	
	class barrier_part:public rectangle_battle::collision_mgr::collision_obj
	{
		private:
		kos_gfx::pvr::texture_fragment img;
		rectangle_battle::collision_mgr::element collision_elem;
		
		public:
		barrier_part(kos_gfx::pvr::texture_fragment tex)
		{
			img=tex;
			dmg=0;
			w=img.w;
			h=img.h;
			collision_elem=rectangle_battle::collision_mgr::register_target(this);
			
			dead=false;
			dying=false;
		};
		
		~barrier_part()
		{
			rectangle_battle::collision_mgr::unregister_target(collision_elem);
		};
		
		void restore()
		{
			dead=false;
		};
		
		void destroy()
		{
			dead=true;
		};
		
		void hit(rectangle_battle::collision_mgr::collision_obj *other)
		{
			if(other->damage()>=0)
				dead=true;
		};
		
		void update(kos_gfx::math::vector2d<> pos, kos_gfx::math::vector2d<> vel)
		{
			position=pos;
			velocity=vel;
		};
		
		void draw()
		{
			if(!dead)
				kos_gfx::pvr::draw(img,position.x,position.y);
		};
	};
	
	class barrier
	{
		private:
		std::vector<barrier_part*> parts;
		
		kos_gfx::math::vector2d<> position;
		int dist_x, dist_y, elem_w;
		
		ORIENTATION orient;
		
		bool dead;
		
		public:
		barrier()
		{
			dead=true;
		};
		
		barrier(kos_gfx::pvr::texture_fragment tex, int distance_x, int distance_y, int elem_num, int elem_width, ORIENTATION ori=UP)
		{
			create(tex,distance_x,distance_y,elem_num,elem_width,ori);
		};
		
		~barrier()
		{
			for(int i=0;i<parts.size();++i)
				delete parts[i];
		};
		
		void create(kos_gfx::pvr::texture_fragment tex, int distance_x, int distance_y, int elem_num, int elem_width,ORIENTATION ori=UP)
		{
			dead=false;
			orient=ori;
			dist_x=distance_x;
			dist_y=distance_y;
			elem_w=elem_width;
			
			std::vector<barrier_part*> tmp;
			tmp.swap(parts); //should force the memory previously occupied by the vector to be freed;
			for(int i=0;i<tmp.size();++i)
				delete tmp[i];
				
			parts.resize(elem_num);
			for(int i=0;i<elem_num;++i)
				parts[i]=new barrier_part(tex);
		};
		
		void restore()
		{
			dead=false;
			for(std::vector<barrier_part*>::iterator it=parts.begin();it!=parts.end();++it)
			{
				(*it)->restore();
			};
		};
		
		void destroy()
		{
			dead=true;
			for(std::vector<barrier_part*>::iterator it=parts.begin();it!=parts.end();++it)
			{
				(*it)->destroy();
			};
		};
		
		void draw()
		{
			if(!dead)
			{
				for(std::vector<barrier_part*>::iterator it=parts.begin();it!=parts.end();++it)
				{
					(*it)->draw();
				};
			};
		};
		
		void update(kos_gfx::math::vector2d<> pos, kos_gfx::math::vector2d<> vel, double w, double h)
		{
			if(!dead)
			{
				for(int i=0;i<parts.size();++i)
				{
					parts[i]->update(kos_gfx::math::vector2d<>(pos.x+dist_x+w/2+i*elem_w-elem_w*parts.size()/2,(orient==UP?-elem_w:h)+pos.y+dist_y),vel);
				};
			};
		};
	};
	
};
