//===============================================================================
//collects a resourcelist to give to a manufacturing schematic
//
void CraftingSession::updateResourceContainer(uint64 containerID, uint32 newAmount)
{
// destroy if its empty
    if(!newAmount)
    {
		ResourceContainer*		resContainer	= dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(containerID));
		TangibleObject*			container		= dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));
        //now destroy it client side
		gContainerManager->deleteObject(resContainer, container);

    }
    // update it
    else
    {
        ResourceContainer*			resContainer	= dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(containerID));

        resContainer->setAmount(newAmount);
        gMessageLib->sendResourceContainerUpdateAmount(resContainer,mOwner);
        mDatabase->executeSqlAsync(NULL,NULL,"UPDATE %s.resource_containers SET amount=%u WHERE id=%" PRIu64 "",mDatabase->galaxy(),newAmount,resContainer->getId());
       
    }

}
void CraftingSession::handleFillSlotResource(uint64 resContainerId,uint32 slotId,uint32 unknown,uint8 counter)
{
    // update resource container
    ResourceContainer*			resContainer	= dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(resContainerId));
    ManufactureSlot*			manSlot			= mManufacturingSchematic->getManufactureSlots()->at(slotId);

    FilledResources::iterator	filledResIt		= manSlot->mFilledResources.begin();

    //bool resourceBool = false;
    bool smallupdate = false;

    if(!resContainer)
    {
        gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
    }

    if(!manSlot)
    {
        gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Invalid_Slot,counter,mOwner);
    }


    uint32	availableAmount		= resContainer->getAmount();
    uint32	totalNeededAmount	= manSlot->mDraftSlot->getNecessaryAmount();
    uint32	existingAmount		= 0;
    uint64	containerResId		= resContainer->getResourceId();

    // see if something is filled already
    existingAmount = manSlot->getFilledAmount();

    // update the needed amount
    totalNeededAmount -= existingAmount;

    // fail if its already complete
    if(!totalNeededAmount)
    {
        gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Slot_Already_Full,counter,mOwner);
        return;
    }

    //check whether we have the same resource - no go if its different - check for the slot being empty though
    if(manSlot->getResourceId() && (containerResId != manSlot->getResourceId()))
    {
        gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Internal_Invalid_Ingredient,counter,mOwner);
        return;
    }

    // see how much this container has to offer
    // slot completely filled
    if(availableAmount >= totalNeededAmount)
    {
        // add to the filled resources
        filledResIt				= manSlot->mFilledResources.begin();

        while(filledResIt != manSlot->mFilledResources.end())
        {
            // already got something of that type filled
            if(containerResId == (*filledResIt).first)
            {
                //hark in live the same resource gets added to a second slot
                manSlot->mFilledResources.push_back(std::make_pair(containerResId,totalNeededAmount));
                filledResIt				= manSlot->mFilledResources.begin();
                manSlot->setFilledType(DST_Resource);//4  resource has been filled
                smallupdate = true;
                break;
            }

            ++filledResIt;
        }


        // nothing of that resource filled, add a new entry
        if(filledResIt == manSlot->mFilledResources.end())
        {
            //resourceBool = true;
            // only allow one unique type
            if(manSlot->mFilledResources.empty())
            {
                manSlot->mFilledResources.push_back(std::make_pair(containerResId,totalNeededAmount));
                manSlot->setFilledType(DST_Resource);
                manSlot->mFilledIndicatorChange = true;
            }
            else
            {
                gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Bad_Resource_Chosen,counter,mOwner);
                return;
            }
        }

        // update the container amount
        uint32 newContainerAmount = availableAmount - totalNeededAmount;

        // destroy if its empty
        if(!newContainerAmount)
        {
            //now destroy it client side
			TangibleObject* container = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));

            //just delete it
			gContainerManager->deleteObject(resContainer, container);

        }
        // update it
        else
        {
            resContainer->setAmount(newContainerAmount);
            gMessageLib->sendResourceContainerUpdateAmount(resContainer,mOwner);
            mDatabase->executeSqlAsync(NULL,NULL,"UPDATE %s.resource_containers SET amount=%u WHERE id=%" PRIu64 "",mDatabase->galaxy(),newContainerAmount,resContainer->getId());
            
        }

        // update the slot total resource amount
        manSlot->setFilledAmount(manSlot->mDraftSlot->getNecessaryAmount());

        // update the total count of filled slots
        mManufacturingSchematic->addFilledSlot();
        gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
    }
    // got only a bit
    else
    {
        // add to the filled resources
        uint64 containerResId	= resContainer->getResourceId();
        filledResIt				= manSlot->mFilledResources.begin();

        while(filledResIt != manSlot->mFilledResources.end())
        {
            // already got something of that type filled
            if(containerResId == (*filledResIt).first)
            {
                //(*filledResIt).second += availableAmount;
                manSlot->mFilledResources.push_back(std::make_pair(containerResId,availableAmount));
                filledResIt				= manSlot->mFilledResources.begin();
                manSlot->setFilledType(DST_Resource);
                smallupdate = true;
                break;
            }

            ++filledResIt;
        }

        // nothing of that resource filled, add a new entry
        if(filledResIt == manSlot->mFilledResources.end())
        {
            // only allow one unique type
            if(manSlot->mFilledResources.empty())
            {
                manSlot->mFilledResources.push_back(std::make_pair(containerResId,availableAmount));
                manSlot->setFilledType(DST_Resource);
            }
            else
            {
                gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Bad_Resource_Chosen,counter,mOwner);
                return;
            }
        }

        // destroy the container as its empty now
		TangibleObject* container = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));
		gContainerManager->deleteObject(resContainer, container);

        // update the slot total resource amount
        manSlot->mFilled += availableAmount;
    }

    // update the slot contents, send all slots on first fill
    // we need to make sure we only update lists with changes, so the lists dont desynchronize!
    if(!mFirstFill)
    {
        mFirstFill = true;
        gMessageLib->sendDeltasMSCO_7(mManufacturingSchematic,mOwner);
    }
    else if(smallupdate == true)
    {
        gMessageLib->sendManufactureSlotUpdateSmall(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
    }
    else
    {
        gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
    }

    // done
    gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_None,counter,mOwner);

}
void ObjectController::_handleResourceContainerSplit(uint64 targetId,Message* message,ObjectControllerCmdProperties* cmdProperties)
{
	PlayerObject*		playerObject		= dynamic_cast<PlayerObject*>(mObject);
	ResourceContainer*	selectedContainer	= dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(targetId));

	Inventory* inventory = dynamic_cast<Inventory*>(playerObject->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory));

	gLogger->logMsgF("ObjectController::_handleResourceContainerSplit: Container : %I64u",MSG_NORMAL,targetId);

	if(!selectedContainer)
	{
		gLogger->logMsg("ObjectController::_handleResourceContainerSplit: Container does not exist!");
		return;
	}

	string dataStr;

	message->getStringUnicode16(dataStr);
	dataStr.convert(BSTRType_ANSI);

	BStringVector dataElements;
	uint16 elementCount = dataStr.split(dataElements,' ');

	if(!elementCount)
	{
		gLogger->logMsg("ObjectController::_handleResourceContainerSplit: Error in requestStr");
		return;
	}

	uint32	splitOffAmount	= boost::lexical_cast<uint32>(dataElements[0].getAnsi());
	uint64	parentId		= boost::lexical_cast<uint64>(dataElements[1].getAnsi());


	if(selectedContainer->getParentId() == inventory->getId())
	{
		//check if we can fit an additional resource container in our inventory
		if(!inventory->checkSlots(1))
		{
			gMessageLib->sendSystemMessage(playerObject,L"","error_message","inv_full");
			return;
		}

		mDatabase->ExecuteSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",selectedContainer->getAmount(),selectedContainer->getId());

		// create a new one
		// update selected container contents
		selectedContainer->setAmount(selectedContainer->getAmount() - splitOffAmount);
		gMessageLib->sendResourceContainerUpdateAmount(selectedContainer,playerObject);

		gObjectFactory->requestNewResourceContainer(inventory,(selectedContainer->getResource())->getId(),parentId,99,splitOffAmount);
		return;
	}

	Item* item = dynamic_cast<Item*>(gWorldManager->getObjectById(parentId));
	if(!item)
	{
		gLogger->logMsg("ObjectController::_ExtractObject: resourcecontainers parent does not exist!");
		assert(false && "ObjectController::_ExtractObject resourcecontainers parent does not exist");
		return;
	}
	
	if(!item->checkCapacity())
	{
		//check if we can fit an additional item in our inventory
		gMessageLib->sendSystemMessage(playerObject,L"","container_error_message","container3");
		return;
	}
	// update selected container contents
	selectedContainer->setAmount(selectedContainer->getAmount() - splitOffAmount);

	gMessageLib->sendResourceContainerUpdateAmount(selectedContainer,playerObject);

	gObjectFactory->requestNewResourceContainer(item,(selectedContainer->getResource())->getId(),parentId,99,splitOffAmount);
	
}