# Breathnuts script by Mindee
# http://mindee-bot.com
#
# [INFO]
# Script uses breathnut when breathnut effect is about to run out (30s).
# It also makes sure that one breathnut is always in backpack. (Retrieves from inventory)
# When only one breathnut is left and it's time to use it, bot logs out to keep one last breathnut for emergency.

BreathNut = 2606

def onScriptActivation():
	DisplayInfo()
	RunRetrieve(5000)
	
def onConnect():
	DisplayInfo()

def DisplayInfo():
	if script.ReceivedInventory():
		count = script.GetItemsCountWithInventory(BreathNut)
		if count < 2:
			script.Alarm('You have ' + str(count) + ' breathnuts in your backpack/inventory!\nScript will not work!', 'Error!')
			return

		script.StatusMessage('Breathnuts left: ' + str(count))
	else:
		script.RunEvent('DisplayInfo', 1000)

def onReceiveGameMessage(text):
	if 'The breathnuts effect will expire in 1 minute' in text:
		script.RunEvent('UseBreathnut', 30000)

def onReceiveGroundText(x, y, z, type, text):
	if 'Aarghll' in text and not script.GetVar('running'):
		script.RunEvent('UseBreathnut', 1000)

def RunRetrieve(time):
	script.RunEvent('Retrieve', time)

def Retrieve():
	if not script.ReceivedInventory():
		RunRetrieve(5000)
		return

	countBackpack = script.GetItemsCount(BreathNut, False)
	if countBackpack > 0:
		RunRetrieve(5000)
		return

	totalCount = script.GetItemsCountWithInventory(BreathNut)
	inventoryCount = totalCount - countBackpack
	if inventoryCount == 0:
		return

	status = script.RetrieveItem(BreathNut)
	RunRetrieve(5000)
	
def UseBreathnut():
	if script.GetVar('running'): return
	
	if not script.ReceivedInventory():
		script.SetVar('running', False)
		script.RunEvent('UseBreathnut', 5000)
		return

	script.SetVar('running', True)
	totalCount = script.GetItemsCountWithInventory(BreathNut)

	if totalCount < 2:
		script.Alarm('You only have ' + str(totalCount) + ' breathnuts!\nLogging out.')
		script.Logout()
		script.SetVar('running', False)
		return

	countBackpack = script.GetItemsCount(BreathNut, False)
	if countBackpack == 0: # didn't retrieve yet? try again in 1 second.
		script.SetVar('running', False)
		script.RunEvent('UseBreathnut', 1000)
		return

	script.SetVar('running', False)
	if script.UseItemId(BreathNut):
		script.StatusMessage('Used breathnut.\nBreathnuts left: ' + str(totalCount - 1))
	else:
		script.StatusMessage('Failed using breathnut. Trying again in a second.')
		script.RunEvent('UseBreathnut', 1000)
