void StructureManager::handleObjectReady(Object* object,DispatchClient* client)
{
	PlayerStructure* structure = dynamic_cast<PlayerStructure*>(object);

	if(!structure)
	{
			gLogger->logMsg("StructureManager::handleObjectReady: No structure");
	}

	if(gWorldManager->getWMState() == WMState_Running)
	{
		// set timer for deletion of building fence

		uint32 account = client->getAccountId();
		PlayerObject* player = gWorldManager->getPlayerByAccId(account);

		PlayerStructure* fence =  gNonPersistantObjectFactory->requestBuildingFenceObject(structure->mPosition.x,structure->mPosition.y,structure->mPosition.z, player);
		structure->getTTS()->todo = ttE_BuildingFence;
		structure->getTTS()->buildingFence = fence->getId();
		structure->getTTS()->playerId = player->getId();
		structure->getTTS()->projectedTime = mBuildingFenceInterval + Anh_Utils::Clock::getSingleton()->getLocalTime();

		gWorldManager->handleObjectReady(structure,player->getClient());

		addStructureforConstruction(structure->getId());
	}
	else
	{
		gWorldManager->handleObjectReady(structure,NULL);
	}
}
//======================================================================================================================
//
// Modifies the Admin List
//
void	ObjectController::_handleTransferStructure(uint64 targetId,Message* message,ObjectControllerCmdProperties* cmdProperties)
{
    // requirement we have the structure targeted AND give the name of the recipient on the commandline
    // OR we have the recipient targeted and stand NEXT to the structure were about to transfer

    //do we have a valid donor ?
    CreatureObject* creature  = dynamic_cast<CreatureObject*>(mObject); PlayerObject* player = creature->GetGhost();

    if(!player)
    {
        return;
    }


    // is the player online and near 30m ?
    // we get the  players id as targetid if yes, otherwise we get the name as string
    // however, we do not want players that  are not online

    //now get the target player
    PlayerObject*	recipient	= dynamic_cast<PlayerObject*>(gWorldManager->getObjectById(targetId));

    if(!recipient)
    {
        gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "no_transfer_target"), player);
        return;
    }

    //do we have a valid structure ??? check our target first
    uint64 id = player->GetCreature()->getTargetId();
    Object* object = gWorldManager->getObjectById(id);
    PlayerStructure* structure = dynamic_cast<PlayerStructure*>(object);

    if(!structure)
    {
        // we need to get the nearest structure that we own
        // for now dustoff
        gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "command_no_building"), player);
        return;
    }

    //is the structure in Range???
    float fTransferDistance = gWorldConfig->getConfiguration<float>("Player_Transfer_Structure_Distance",(float)8.0);
    if(glm::distance(player->GetCreature()->mPosition, structure->mPosition) > fTransferDistance)
    {
        gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "command_no_building"), player);
        return;
    }

    StructureAsyncCommand command;
    command.PlayerId = player->getId();
    command.StructureId = structure->getId();
    command.RecipientId = recipient->getId();
    command.PlayerStr = recipient->GetCreature()->getFirstName();
    command.Command = Structure_Command_TransferStructure;

    gStructureManager->checkNameOnPermissionList(structure->getId(),player->getId(),player->GetCreature()->getFirstName(),"ADMIN",command);

}
//======================================================================================================================
//
// Modifies the Admin List
//
void	ObjectController::_handleNameStructure(uint64 targetId,Message* message,ObjectControllerCmdProperties* cmdProperties)

{
    // requirement we have the structure targeted AND give the name of the recipient on the commandline
    // OR we have the recipient targeted and stand NEXT to the structure were about to transfer

    //do we have a valid donor ?
    CreatureObject* creature  = dynamic_cast<CreatureObject*>(mObject); PlayerObject* player = creature->GetGhost();

    if(!player)
    {
        return;
    }

    //do we have a valid structure ??? check our target first
    uint64 id = player->GetCreature()->getTargetId();
    Object* object = gWorldManager->getObjectById(id);
    PlayerStructure* structure = dynamic_cast<PlayerStructure*>(object);

    if(!structure)
    {
        gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "command_no_building"), player);
        return;
    }

    //is the structure in Range???
    float fTransferDistance = gWorldConfig->getConfiguration<float>("Player_Structure_Operate_Distance",(float)10.0);
    if(glm::distance(player->GetCreature()->mPosition, structure->mPosition) > fTransferDistance)
    {
        gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "command_no_building"), player);
        return;
    }

    //find out where our structure is
    BString dataStr;
    message->getStringUnicode16(dataStr);

    BString nameStr;

    dataStr.convert(BSTRType_ANSI);

    sscanf(dataStr.getAnsi(),"%s",nameStr.getAnsi());

    if(nameStr.getLength() > 68)
    {
        gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "not_valid_name"), player);
        return;
    }

    StructureAsyncCommand command;
    command.Command = Structure_Command_RenameStructure;
    command.PlayerId = player->getId();
    command.StructureId = structure->getId();

    gStructureManager->checkNameOnPermissionList(structure->getId(),player->getId(),player->GetCreature()->getFirstName(),"ADMIN",command);

}
//======================================================================================================================
//
// provides the harvester with the current resources
//
void	ObjectController::_handleHarvesterGetResourceData(uint64 targetId,Message* message,ObjectControllerCmdProperties* cmdProperties)
{

    PlayerObject*	player	= dynamic_cast<PlayerObject*>(mObject);

    if(!player)
    {
        return;
    }

    //do we have a valid structure ???
    uint64 id = targetId;
    Object* object = gWorldManager->getObjectById(id);
    PlayerStructure* structure = dynamic_cast<PlayerStructure*>(object);

    if(!structure)
    {
        //gMessageLib->sendSystemMessage(player,L"","player_structure","command_no_building");
        return;
    }

    //is the structure in Range???
    float fTransferDistance = gWorldConfig->getConfiguration<float>("Player_Structure_Operate_Distance",(float)10.0);
    if(glm::distance(player->mPosition, structure->mPosition) > fTransferDistance)
    {
        DLOG(INFO) << " ObjectController::_handleHarvesterGetResourceData Structure not in Range";
        return;
    }

    HarvesterObject* harvester = dynamic_cast<HarvesterObject*>(structure);

    StructureAsyncCommand command;

    command.Command = Structure_Command_GetResourceData;
    command.PlayerId = player->getId();
    command.StructureId = structure->getId();

    gStructureManager->checkNameOnPermissionList(structure->getId(),player->getId(),player->getFirstName().getAnsi(),"ADMIN",command);

    return;
    gMessageLib->sendHarvesterResourceData(structure,player);

    DLOG(INFO) << " ObjectController::_handleHarvesterGetResourceData :: hino 7 baseline";
    gMessageLib->sendBaselinesHINO_7(harvester,player);

    //add the structure to the timer so the resource amounts are updated while we look at the hopper
    //harvester->getTTS()->todo		= ttE_UpdateHopper;
    //harvester->getTTS()->playerId	= player->getId();
    //structure->getTTS()->projectedTime = 5000 + Anh_Utils::Clock::getSingleton()->getLocalTime();
    //gStructureManager->addStructureforHopperUpdate(harvester->getId());

    // this needs to be handled zoneserverside - otherwise the addition of a res will trigger a racecondition
    // between the sql write query and the sql read please note that the harvesting itself happens through stored procedures
    // and we cant keep the updatecounters synchronized


}
//======================================================================================================================
//
// Discards the contents of a harvesters Hopper
//
void	ObjectController::_handleDiscardHopper(uint64 targetId,Message* message,ObjectControllerCmdProperties* cmdProperties)
{

    CreatureObject* creature  = dynamic_cast<CreatureObject*>(mObject); PlayerObject* player = creature->GetGhost();

    if(!player)
    {
        return;
    }

    //do we have a valid structure ???
    uint64 id = targetId;
    Object* object = gWorldManager->getObjectById(id);
    PlayerStructure* structure = dynamic_cast<PlayerStructure*>(object);

    if(!structure)
    {
        //gMessageLib->sendSystemMessage(player,L"","player_structure","command_no_building");
        return;
    }

    //is the structure in Range???
    float fTransferDistance = gWorldConfig->getConfiguration<float>("Player_Structure_Operate_Distance",(float)10.0);
    if(glm::distance(player->GetCreature()->mPosition, structure->mPosition) > fTransferDistance)
    {
        return;
    }

    StructureAsyncCommand command;

    command.Command = Structure_Command_DiscardHopper;
    command.PlayerId = player->getId();
    command.StructureId = structure->getId();

    gStructureManager->checkNameOnPermissionList(structure->getId(),player->getId(),player->GetCreature()->getFirstName(),"ADMIN",command);


}
void StructureManager::_HandleStructureDestruction(StructureManagerAsyncContainer* asynContainer,DatabaseResult* result)
{
	struct structData
	{
		uint64 id;
		uint32 condition;
	};

	structData sd;

	DataBinding* binding = mDatabase->CreateDataBinding(2);
	binding->addField(DFT_uint64,offsetof(structData,id),8,0);
	binding->addField(DFT_uint32,offsetof(structData,condition),4,1);

	uint64 count;
	count = result->getRowCount();

	for(uint64 i = 0;i < count;i++)
	{
		result->GetNextRow(binding,&sd);

		PlayerStructure* structure = dynamic_cast<PlayerStructure*>(gWorldManager->getObjectById(sd.id));
		if(structure)
		{
			gLogger->logMsgF("StructureManager::delete structure due to zero condition %I64u",MSG_NORMAL,structure->getId());
			//delete the deed in the db
			//the parent is the structure and the item family is 15
			int8 sql[100];
			sprintf(sql,"DELETE FROM items WHERE parent_id = %"PRIu64" AND item_family = 15",structure->getId());
			mDatabase->ExecuteSqlAsync(NULL,NULL,sql);

			//delete harvester db side with all power and all resources
			gObjectFactory->deleteObjectFromDB(structure);
			UpdateCharacterLots(structure->getOwner());

			//delete it in the world
			gMessageLib->sendDestroyObject_InRangeofObject(structure);
			gWorldManager->destroyObject(structure);


								
		}
	}

	mDatabase->DestroyDataBinding(binding);
}
//======================================================================================================================
//
// Modifies the Admin List
//
void	ObjectController::_handleModifyPermissionList(uint64 targetId,Message* message,ObjectControllerCmdProperties* cmdProperties)

{

    CreatureObject* creature  = dynamic_cast<CreatureObject*>(mObject); PlayerObject* player = creature->GetGhost();

    if(!player)
    {
        DLOG(info) << " ObjectController::_handleModifyPermissionList Player not found";
        return;
    }

    //find out where our structure is
    BString dataStr;
    message->getStringUnicode16(dataStr);

    BString playerStr,list,action;

    dataStr.convert(BSTRType_ANSI);

    int8 s1[64],s2[32],s3[32];
    sscanf(dataStr.getAnsi(),"%32s %16s %16s",s1, s2, s3);
    playerStr = s1;
    list = s2;
    action = s3;

    if(playerStr.getLength() > 40)
    {
        gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "permission_40_char"), player);
        return;
    }

    //TODO is target a structure?? used when using the commandline option
    uint64 id = player->GetCreature()->getTargetId();
    Object* object = gWorldManager->getObjectById(id);
    PlayerStructure* structure = dynamic_cast<PlayerStructure*>(object);

    //if we have no structure that way, see whether we have a structure were we just used the adminlist
    if(!structure)
    {
        id = player->getStructurePermissionId();
        Object* object = gWorldManager->getObjectById(id);
        structure = dynamic_cast<PlayerStructure*>(object);
    }

    if(!structure)
    {
        return;
    }

    //is the structure in Range???
    float fAdminListDistance = gWorldConfig->getConfiguration<float>("Player_Admin_List_Distance",(float)32.0);

    if(player->getParentId())
    {
        if(CellObject* cell = dynamic_cast<CellObject*>(gWorldManager->getObjectById(player->getParentId())))
        {
            if(HouseObject* house = dynamic_cast<HouseObject*>(gWorldManager->getObjectById(cell->getParentId())))
            {
                if(house->getId() != structure->getId())
                {
                    gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "command_no_building"), player);
                    return;
                }
            }
        }

    }
    else if(glm::distance(player->GetCreature()->mPosition, structure->mPosition) > fAdminListDistance)
    {
        gMessageLib->SendSystemMessage(::common::OutOfBand("player_structure", "command_no_building"), player);
        return;
    }

    player->setStructurePermissionId(0);

    StructureAsyncCommand command;
    command.PlayerId = player->getId();
    command.StructureId = structure->getId();
    command.List = list;
	command.PlayerStr = playerStr.getAnsi();

    if(action == "add")
    {
        command.Command = Structure_Command_AddPermission;
        gStructureManager->checkNameOnPermissionList(structure->getId(),player->getId(),player->GetCreature()->getFirstName(),"ADMIN",command);
		//addNametoPermissionList(command.StructureId, command.PlayerId, command.PlayerStr, command.List);
    }

    if(action == "remove")
    {
        command.Command = Structure_Command_RemovePermission;
        gStructureManager->checkNameOnPermissionList(structure->getId(),player->getId(),player->GetCreature()->getFirstName(),"ADMIN",command);
    }

}
void	ObjectController::handleResourceEmptyHopper(Message* message)
{
    uint64 playerId;
    uint64 harvesterId;

    message->getUint64(playerId);
    message->getUint64(harvesterId);

    CreatureObject* creature  = dynamic_cast<CreatureObject*>(mObject); PlayerObject* player = creature->GetGhost();

    if(!player)
    {
        return;
    }

    //do we have a valid structure ???
    Object* object = gWorldManager->getObjectById(harvesterId);
    PlayerStructure* structure = dynamic_cast<PlayerStructure*>(object);

    if(!structure)
    {
        //gMessageLib->sendSystemMessage(player,L"","player_structure","command_no_building");
        return;
    }

    //is the structure in Range???
    float fTransferDistance = gWorldConfig->getConfiguration<float>("Player_Structure_Operate_Distance",(float)10.0);
    if(glm::distance(player->GetCreature()->mPosition, structure->mPosition) > fTransferDistance)
    {
        return;
    }

    uint64 resourceId;
    uint32 amount;
    uint8 b1, b2;

    message->getUint64(resourceId);
    message->getUint32(amount);
    message->getUint8(b1);
    message->getUint8(b2);

    StructureAsyncCommand command;

    if(b1 == 0)
    {
        command.Command		=	Structure_Command_RetrieveResource;
        command.PlayerId	=	player->getId();
        command.StructureId =	structure->getId();
        command.ResourceId	=	resourceId;
        command.Amount		=	amount;
        command.b1 = b1;
        command.b2 = b2;
    }
    if(b1 == 1)
    {
        command.Command		=	Structure_Command_DiscardResource;
        command.PlayerId	=	player->getId();
        command.StructureId =	structure->getId();
        command.ResourceId	=	resourceId;
        command.Amount		=	amount;
        command.b1 = b1;
        command.b2 = b2;

    }

    gStructureManager->checkNameOnPermissionList(structure->getId(),player->getId(),player->GetCreature()->getFirstName(),"HOPPER",command);

}