void LootkitObjectImplementation::createItem() {
    for (int i = 0; i<comps.size(); ++i) {
        if (components.get(comps.get(i)) == 0) {
            return; // Still missing pieces
        }
    }
    ManagedReference<CreatureObject*>  player = getPlayer();
    if (player != NULL) {

        player->sendSystemMessage("@loot_kit:new_item_created");

        ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory");
        ZoneServer* zoneServer = server->getZoneServer();

        ManagedReference<SceneObject*> rewardObject = zoneServer->createObject(reward.get(System::random(reward.size()-1)), 2);

        Locker clocker(inventory, player);
        rewardObject->sendTo(player, true);
        if (inventory->transferObject(rewardObject, -1, true)) {
            //getParent()->removeObject(_this, true);
            destroyObjectFromWorld(true);

            if (isPersistent())
                destroyObjectFromDatabase(true);
        }
    }
}
bool CampSiteActiveAreaImplementation::despawnCamp() {
	Locker locker(_this.get());

	if(!abandoned && campOwner != NULL && campOwner->getZoneServer() != NULL) {
		/// Get Player Manager
		PlayerManager* playerManager = campOwner->getZoneServer()->getPlayerManager();
		if (playerManager == NULL) {
			error("playerManager is null");
			return false;
		}

		float durationUsed = ((float)(System::getTime() - timeCreated)) / (campStructureData->getDuration() / 4);
		if (durationUsed > 1)
			durationUsed = 1;

		int amount = 0;
		int campXp = campStructureData->getExperience();
		amount = (int)(campXp * durationUsed);

		amount += (int)((visitors.size() -1) * (campXp / 30) * durationUsed);
		amount += (int)(currentXp * durationUsed);

		playerManager->awardExperience(campOwner, "camp", amount, true);
	}

	Locker tlocker(&taskMutex);

	if(despawnTask != NULL ) {
		if(despawnTask->isScheduled())
			despawnTask->cancel();
		despawnTask = NULL;
	}


	if(abandonTask != NULL) {
		if(abandonTask->isScheduled())
			abandonTask->cancel();
		abandonTask = NULL;
	}

	tlocker.release();

	if(campOwner != NULL)
		campOwner->dropObserver(ObserverEventType::STARTCOMBAT, campObserver);

	if (camp != NULL) {
		if(camp->getZone() == NULL)
			return false;

		StructureManager::instance()->destroyStructure(camp);
	}

	destroyObjectFromWorld(true);
	destroyObjectFromDatabase(true);


	return true;
}
void ResourceDeedImplementation::destroyDeed() {
	if (parent.get() != NULL) {
		destroyObjectFromWorld(true);
	}

	if (isPersistent())
		destroyObjectFromDatabase(true);

	generated = true;
}
void ResourceDeedImplementation::destroyDeed() {
	if (parent.get() != NULL) {
		/*getParent()->removeObject(_this.getReferenceUnsafeStaticCast(), true);
		broadcastDestroy(_this.getReferenceUnsafeStaticCast(), false);*/
		destroyObjectFromWorld(true);
	}

	if (isPersistent())
		destroyObjectFromDatabase(true);

	generated = true;
}
void PlantObjectImplementation::changeSize(int size) {
	String plantTemplate = "";

	switch (size) {
	case 0: plantTemplate = "object/tangible/loot/plant_grow/plant_stage_dead.iff"; break;
	case 1: plantTemplate = "object/tangible/loot/plant_grow/plant_stage_1.iff"; break;
	case 2: plantTemplate = "object/tangible/loot/plant_grow/plant_stage_2.iff"; break;
	case 3: plantTemplate = "object/tangible/loot/plant_grow/plant_stage_3.iff"; break;
	}

	ManagedReference<ZoneServer*> zoneServer = getZoneServer();

	if (zoneServer == NULL)
		return;

	ManagedReference<SceneObject*> parent = getParent();

	if (parent == NULL || !parent->isCellObject())
		return;

	ManagedReference<SceneObject*> obj = zoneServer->createObject(plantTemplate.hashCode(), getPersistenceLevel());

	if (obj == NULL)
		return;

	Locker clocker(obj, _this.getReferenceUnsafeStaticCast());

	obj->initializePosition(getPositionX(), getPositionZ(), getPositionY());
	obj->setDirection(Math::deg2rad(getDirectionAngle()));

	ManagedReference<PlantObject*> newPlant = cast<PlantObject*>( obj.get());

	if (newPlant == NULL)
		return;

	newPlant->setWaterLevel(waterLevel);
	newPlant->setNutrientLevel(nutrientLevel);
	newPlant->setWaterQuality(waterQuality);
	newPlant->setNutrientQuality(nutrientQuality);
	newPlant->setPlantHealth(health);

	newPlant->initializePlant(size);

	parent->transferObject(obj, -1);

	clocker.release();

	destroyObjectFromWorld(true);
	destroyObjectFromDatabase();
}
void TangibleObjectImplementation::setUseCount(uint32 newUseCount, bool notifyClient) {
	if (useCount == newUseCount)
		return;

	setCountdownTimer(newUseCount, notifyClient);

	if (useCount < 1 && !isCreatureObject()) {
		destroyObjectFromWorld(true);

		destroyObjectFromDatabase(true);

		return;
	}
}
void ResourceContainerImplementation::setQuantity(uint32 quantity, bool doNotify, bool ignoreMax) {
	Locker _locker(_this.get());
	ManagedReference<SceneObject*> parent = getParent();
	stackQuantity = quantity;

	if(stackQuantity < 1) {

		if(parent != NULL) {
			/*parent->broadcastDestroy(_this.get(), true);
			parent->removeObject(_this.get(), false);*/
			//setParent(NULL);

			destroyObjectFromWorld(true);
		}

		destroyObjectFromDatabase(true);
		return;
	}

	int newStackSize = 0;

	if (!ignoreMax && stackQuantity > ResourceContainer::MAXSIZE) {

		newStackSize = stackQuantity - ResourceContainer::MAXSIZE;
		stackQuantity = ResourceContainer::MAXSIZE;
	}

	if (newStackSize > 0) {
		if (parent != NULL) {

			ResourceContainer* harvestedResource = spawnObject->createResource(newStackSize);

			parent->transferObject(harvestedResource, -1, true);
			parent->broadcastObject(harvestedResource, true);
		}
	}

	if(!doNotify)
		return;

	ResourceContainerObjectDeltaMessage3* rcnod3 =
			new ResourceContainerObjectDeltaMessage3(_this.get());

	rcnod3->updateQuantity();
	rcnod3->close();

	broadcastMessage(rcnod3, true);
}
void FireworkObjectImplementation::completeLaunch(CreatureObject* player, int removeDelay) {
	ManagedReference<StaticObject*> launcherObject = (getZoneServer()->createObject(fireworkObject.hashCode(), 0)).castTo<StaticObject*>();

	if (launcherObject == NULL)
		return;

	player->setPosture(CreaturePosture::CROUCHED);
	player->doAnimation("manipulate_low");

	float angle = player->getDirectionAngle();

	if (angle > 360)
		angle = angle - 360;

	float distance = 2.0;

	angle = 2 * M_PI * angle / 360;

	int x = player->getPositionX() + sin(angle) * (distance);
	int y = player->getPositionY() + cos(angle) * (distance);
	int z = player->getZone()->getHeight(x, y);

	Locker locker(launcherObject);

	launcherObject->initializePosition(x, z, y);
	player->getZone()->transferObject(launcherObject, -1, true);

	if (getUseCount() > 1) {
		decreaseUseCount();
	} else {
		destroyObjectFromWorld(true);

		if (isPersistent())
			destroyObjectFromDatabase(true);
	}

	Reference<FireworkRemoveEvent*> fireworkRemoveEvent = new FireworkRemoveEvent(player, launcherObject);
	fireworkRemoveEvent->schedule(removeDelay * 1000);

}
int MissionTerminalImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {
	if (selectedID == 69 && player->hasSkill("combat_smuggler_slicing_01")) {

		if (player->containsActiveSession(SessionFacadeType::SLICING)) {
			player->sendSystemMessage("@slicing/slicing:already_slicing");
			return 0;
		}

		if (!player->checkCooldownRecovery("slicing.terminal")) {
			player->sendSystemMessage("@slicing/slicing:not_again");
			return 0;
		}

		//Create Session
		ManagedReference<SlicingSession*> session = new SlicingSession(player);
		session->initalizeSlicingMenu(player, _this.get());

		return 0;

	}

	if (selectedID == 72) {

		ManagedReference<CityRegion*> city = player->getCityRegion();

		if (city != NULL)
			city->removeMissionTerminal(_this.get());

		destroyObjectFromWorld(true);
		destroyObjectFromDatabase(false);

		return 0;
	}

	return TangibleObjectImplementation::handleObjectMenuSelect(player, selectedID);
}
int DroidDeedImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) {

	if (selectedID == 20) {

		if (generated || !isASubChildOf(player))
			return 1;

		if (player->isInCombat() || player->isRidingMount() || player->isSwimming() || player->isDead() || player->isIncapacitated() ){
			player->sendSystemMessage("@pet/pet_menu:cant_call"); // "You cannot call this pet right now."
			return 1;
		}

		ManagedReference<SceneObject*> datapad = player->getSlottedObject("datapad");

		if (datapad == NULL) {
			player->sendSystemMessage("Datapad doesn't exist when trying to generate droid");
			return 1;
		}

		// Check if this will exceed maximum number of droids allowed
		ManagedReference<PlayerManager*> playerManager = player->getZoneServer()->getPlayerManager();

		int droidsInDatapad = 0;
		int maxStoredDroids = playerManager->getBaseStoredDroids();

		for (int i = 0; i < datapad->getContainerObjectsSize(); i++) {
			Reference<SceneObject*> obj =  datapad->getContainerObject(i).castTo<SceneObject*>();

			if (obj != NULL && obj->isPetControlDevice() ){
				Reference<PetControlDevice*> petDevice = cast<PetControlDevice*>(obj.get());
				if( petDevice != NULL && petDevice->getPetType() == PetManager::DROIDPET){
					droidsInDatapad++;
				}
			}
		}

		if( droidsInDatapad >= maxStoredDroids){
			player->sendSystemMessage("You have too many droids in your datapad");
			return 1;
		}

		Reference<CreatureManager*> creatureManager = player->getZone()->getCreatureManager();
		if( creatureManager == NULL )
			return 1;

		CreatureTemplateManager* creatureTemplateManager = CreatureTemplateManager::instance();
		Reference<CreatureTemplate*> creatureTemplate =  creatureTemplateManager->getTemplate( mobileTemplate.hashCode() );
		if( creatureTemplate == NULL ){
			player->sendSystemMessage("wrong droid template;mobileTemplate=[" + mobileTemplate + "]" );
			return 1;
		}

		Reference<PetControlDevice*> controlDevice = (server->getZoneServer()->createObject(controlDeviceObjectTemplate.hashCode(), 1)).castTo<PetControlDevice*>();
		if( controlDevice == NULL ){
			player->sendSystemMessage("wrong droid control device template " + controlDeviceObjectTemplate);
			return 1;
		}

		Locker locker(controlDevice);

		Reference<CreatureObject*> creatureObject = creatureManager->createCreature(generatedObjectTemplate.hashCode(), true, mobileTemplate.hashCode() );
		if( creatureObject == NULL ){
			controlDevice->destroyObjectFromDatabase(true);
			player->sendSystemMessage("wrong droid templates;mobileTemplate=[" + mobileTemplate + "];generatedObjectTemplate=[" + generatedObjectTemplate + "]" );
			return 1;
		}

		Locker clocker(creatureObject, player);

		Reference<DroidObject*> droid = creatureObject.castTo<DroidObject*>();
		if( droid == NULL ) {
			controlDevice->destroyObjectFromDatabase(true);
			creatureObject->destroyObjectFromDatabase(true);
			return 1;
		}

		droid->loadTemplateData( creatureTemplate );
		droid->setCustomObjectName(StringIdManager::instance()->getStringId(*droid->getObjectName()), true);

		// Transfer crafting components from deed to droid
		ManagedReference<SceneObject*> craftingComponents = getSlottedObject("crafted_components");
		if(craftingComponents != NULL) {
			SceneObject* satchel = craftingComponents->getContainerObject(0);
			// remove all items form satchel and add int he new items
			Vector<ManagedReference<SceneObject*> > toRemove;
			for (int i = 0; i < satchel->getContainerObjectsSize(); ++i) {
				ManagedReference<SceneObject*> sceno = satchel->getContainerObject(i);
				if (sceno != NULL) {
					toRemove.add(sceno);
				}
			}
			satchel->removeAllContainerObjects();
			for(int i=0;i<toRemove.size();i++) {
				SceneObject* component = toRemove.get(i);
				Locker componenetLocker(component);
				component->destroyObjectFromWorld(true);
			}
			// this will change to use stacked modules. we wont care about non droid modules as they arent needed.
			String key;
			ManagedReference<DroidComponent*> comp = NULL;
			HashTableIterator<String, ManagedReference<DroidComponent*> > iterator = modules.iterator();
			droid->setResists(0);
			droid->setHitChance(0);
			for(int i = 0; i < modules.size(); ++i) {
				iterator.getNextKeyAndValue(key, comp);
				if (comp) {
					satchel->transferObject(comp, -1, false);
					DataObjectComponentReference* data = comp->getDataObjectComponent();
					BaseDroidModuleComponent* module = NULL;
					if(data != NULL && data->get() != NULL && data->get()->isDroidModuleData()) {
						module = cast<BaseDroidModuleComponent*>(data->get());
						module->initialize(droid);
					}
				}
			}
			droid->transferObject(craftingComponents, 4, false);
			craftingComponents->setSendToClient(false);
		}
		// Copy color customization from deed to droid
		CustomizationVariables* customVars = getCustomizationVariables();
		if( customVars != NULL ){
			for (int i = 0; i < customVars->size(); ++i) {
				uint8 id = customVars->elementAt(i).getKey();
				int16 val = customVars->elementAt(i).getValue();

				String name = CustomizationIdManager::instance()->getCustomizationVariable(id);
				if( name.contains( "color" ) ){
					droid->setCustomizationVariable( name, val, true );
				}
			}
			droid->refreshPaint();
		}

		StringId s;
		s.setStringId(droid->getObjectName()->getFullPath());
		controlDevice->setObjectName(s);
		controlDevice->setPetType(PetManager::DROIDPET);
		controlDevice->setMaxVitality(100);
		controlDevice->setVitality(100);
		droid->createChildObjects();
		controlDevice->setControlledObject(droid);
		controlDevice->setDefaultCommands();

		if (!datapad->transferObject(controlDevice, -1)) {
			controlDevice->destroyObjectFromDatabase(true);
			return 1;
		}

		datapad->broadcastObject(controlDevice, true);

		controlDevice->callObject(player);
		droid->initDroidModules(true);
		float maxHam = DroidMechanics::determineHam(overallQuality,species);
		for (int i = 0; i < 9; ++i) {
			if (i % 3 == 0) {
				droid->setBaseHAM(i,maxHam,true);
				droid->setHAM(i,maxHam,true);
			} else {
				droid->setBaseHAM(i,maxHam/100,true);
				droid->setHAM(i,maxHam/100,true);
			}
		}

		//Remove the deed from its container.
		ManagedReference<SceneObject*> deedContainer = getParent().get();

		if (deedContainer != NULL) {
			destroyObjectFromWorld(true);
		}
		generated = true;
		destroyObjectFromDatabase(true);

		player->sendSystemMessage("@pet/pet_menu:device_added"); // "A control device has been added to your datapad."
		return 0;
	}

	return DeedImplementation::handleObjectMenuSelect(player, selectedID);
}