#include "Item.h"
#include "constants.h"

USING_NS_CC;


#define MOVE_ANIM_SIZE 3
#define ANIM_DT	0.5f

Item::Item(void)
{
}

Item::Item(unsigned id,unsigned type,unsigned team,cocos2d::Vec2 position, cocos2d::Node* parent, cocos2d::Vec2 direction, float speed)
{
	char str[100] = {0};

	_id = id;
	sprintf(str, "items/%d.png", id);
	_batch = SpriteBatchNode::create(str);

	SpriteFrameCache* cache = SpriteFrameCache::getInstance();
	sprintf(str, "items/%d.plist", id);
	cache->addSpriteFramesWithFile(str);

	sprintf(str, "I%d_2.png", id);
	_sprite = Sprite::createWithSpriteFrameName(str);
	_batch->addChild(_sprite);
	_sprite->setPosition(position);
	_batch->setPosition(Vec2(0,0));
	parent->addChild(_batch);

	cocos2d::Vector<cocos2d::SpriteFrame*> movement;

	for(int i = 1; i < MOVE_ANIM_SIZE; i++) 
	{
		sprintf(str, "I%d_%d.png", id,i);
		SpriteFrame* frame = cache->getSpriteFrameByName( str );
		movement.pushBack(frame);
	}

	Action* act = RepeatForever::create(
		Animate::create(
			Animation::createWithSpriteFrames(
				movement, 
				ANIM_DT)));
	_sprite->runAction(act);

	_type=type;
	_team=team;
	Vec2 size = Vec2(2*_sprite->getSpriteFrame()->getOriginalSize().width/3, 2*_sprite->getSpriteFrame()->getOriginalSize().height/3);
	_rect=PRect(position,size);
	_used = false;

	if (speed>0)
	{
		
		float last = -_sprite->getSpriteFrame()->getOriginalSize().width/2;
		if (direction.x>0)
			last = -last + g_gameSize.getMaxX();
		float time = abs(last - _sprite->getPosition().x)/speed;

		if (direction.x<0)
		{
			_sprite->setScaleX(-1);
		}

		Sequence* act =  Sequence::createWithTwoActions( 
		MoveBy::create(time, direction*speed*time),
		CallFunc::create(std::bind(&Item::setUsed,this)));

		_sprite->runAction(act);
	}
}

Item::~Item(void)
{
	_batch->getParent()->removeChild(_batch);
	//_batch->removeAllChildrenWithCleanup(false);
}

void Item::setUsed()
{
	_used= true;
}

bool Item::isUsed()
{
	return _used;
}

PRect* Item::getRect()
{
	return &_rect;
}

int Item::getType()
{
	return _type;
}

int Item::getTeam()
{
	return _team;
}

void Item::UpdateRect()
{
	_rect.center = _sprite->getPosition();
}

void Item::UpdateZOrder(unsigned z)
{
	_batch->setZOrder(z);
}

bool compareItemByZOrder(Item* u1,Item* u2)
{
	return (u1->_sprite->getPosition().y > 
		u2->_sprite->getPosition().y);
}