
class 'popcornMachine' (Appliance)

popcornMachine.maxStock = 4
popcornMachine.stock = 4
popcornMachine.timePerFill = 750
popcornMachine.fillTimer = 0

function popcornMachine:__init() super()
end

function popcornMachine:__finalize()
end

function popcornMachine:onCreate()
	Appliance.onCreate(self)
	self:updateAppearance()
end

function popcornMachine:onWorkStart(task)
	
	self:setSelected(false)	
	local diff = self.maxStock - self.stock
	
	if (diff > 0 and Appliance.onWorkStart(self, task)) then
		local totalTime = self.timePerFill * diff
		self.fillTimer = self.timePerFill
		self:clearOverhead()
		self:playSound("SOUND_REFILL_NACHOS_LOOP", true)		
		task:setDuration(totalTime)
		player:setNeverShowHint(ARROW_HINT_POPCORN_MACHINE)
		emily:animate("SHAKETREE", -1, 10)
		return true
	end
	return false
end

function popcornMachine:onWorkUpdate(task, time)
	
	self.fillTimer = self.fillTimer - time
	if (self.fillTimer <= 0) then
		self:adjustStock(1)
		if (self.stock < self.maxStock) then
			self.fillTimer = self.timePerFill
		else
			self.fillTimer = 0
		end
	end
	return Appliance.onWorkUpdate(self, task, time)
end

function popcornMachine:onWorkComplete()
	self.stock = self.maxStock
	self:updateAppearance()
	self:stopSound("SOUND_REFILL_NACHOS_LOOP")
end

function popcornMachine:adjustStock(amount)

	self.stock = self.stock + amount
	if (self.stock > self.maxStock) then
		self.stock = self.maxStock
	elseif (self.stock < 0) then
		self.stock = 0
	end
	
	if (self.stock == 0) then
		hm:placeArrow(ARROW_HINT_POPCORN_MACHINE, self, -4, 40)
	
	end
	
	self:updateAppearance()
	
end

function popcornMachine:updateAppearance()
    -- update appliance visuals
	self:setCurrentFrame(self.stock)
	-- update product visuals
	local prod = getProduct("POPCORN")
	if (prod ~= nil) then
		if (self.stock > 0) then
			prod:animate("PROD_BUT_POPCORN", 0)
		else
			prod:animate("PROD_BUT_POPCORN_EMPTY", 0)
		end
	end	
end

function popcornMachine:onClick()

    self:playSound("SOUND_OBJECT_CLICK")

	if (self.stock < self.maxStock and self:isSelected() == false) then
		Appliance.onClick(self)
		self:setSelected(true)
	end
	
end

function popcornMachine:hasStock()
	return (self.stock > 0)
end
