class 'orderTableEvent' (interface)

orderTableEvent.pool = {}									-- product pool
orderTableEvent.chances = {}								-- product chances
orderTableEvent.timeUntilEnterMin = 0
orderTableEvent.timeUntilEnterMax = 0
orderTableEvent.timeUntilEnter = -1
orderTableEvent.timeUntilNextOrder = 0						-- interval at which the orders come
orderTableEvent.timeUntilEnd = 0							-- time allowed to make all products
orderTableEvent.timeTransfer = 400							-- time it takes to transfer the order
orderTableEvent.numProductsPerOrder = 0						-- number of products ordered each order
orderTableEvent.numOrders = 0								-- total number of orders
orderTableEvent.score = 0									-- score per product
orderTableEvent.endScore = 0								-- score when win
orderTableEvent.subjectImage = nil
orderTableEvent.maxBalloonSize = 0
orderTableEvent.maxBalloonWidth = 3
orderTableEvent.orderOffsetY = 170

orderTableEvent.table = nil
orderTableEvent.order = nil
orderTableEvent.pb = nil
orderTableEvent.pbX = 0
orderTableEvent.pbY = -20
orderTableEvent.countOrders = 0
orderTableEvent.countHanded = 0
orderTableEvent.timer1 = 0
orderTableEvent.timer2 = 0
orderTableEvent.started = false
orderTableEvent.active = false
orderTableEvent.completed = false
orderTableEvent.state = "idle"
orderTableEvent.chanceTotal = 0
orderTableEvent.sequenceStart = nil
orderTableEvent.sequenceWin = nil
orderTableEvent.sequenceLose = nil

function orderTableEvent:__init() super()
end

function orderTableEvent:onLevelInited()

	if (self.table ~= nil) then
	
		-- calculate order position
		x = -self.table:getAnchorX() + self.table:getWidth()/2
		y = -self.table:getAnchorY() + self.orderOffsetY
		
		-- place order
		self.order = createOrder()			
		self.order:setX(x)
		self.order:setY(y)
		self.order:setAnchorPointType(BOTTOMCENTER)		
		self.order:setPivotPointType(BOTTOMCENTER)
		self.order:setMoneyOrder(false)
		self.order:setMaxBalloonWidth(self.maxBalloonWidth)
		self.order:setMaxBalloonSize(self.maxBalloonSize)
		self.order:setVisible(false)
		self.table:addChild(self.order)
	
		-- calculate total chance
		self.chanceTotal = 0
		for index, value in ipairs(self.chances) do
			self.chanceTotal = self.chanceTotal + value
		end  
		
		-- initialize progress bar
		self.pb = createDefaultFillProgressBar();
		self.pb:setProgress(1)	
		self.pb:setX(self.pbX)
		self.pb:setY(self.pbY)
		self.pb:setVisible(false)
		self.table:addChild(self.pb)			
		
		-- initialize event bar
		eventBar:setStartAmount(0)
		eventBar:setTargetAmount(self.timeUntilEnd / 1000)
		eventBar:setProgress(self.timeUntilEnd / 1000)				
		eventBar:setDescriptionText(getText("EVENTBAR"))
		eventBar:setSubjectImage(self.subjectImage, player:getCurrentResourceSection())
		
		-- initialize timer
		if (self.timeUntilEnterMin > 0) then		
			self.timeUntilEnter = getRandomRange(self.timeUntilEnterMin, self.timeUntilEnterMax)			
		end
	
	else
	
		warn("orderTableEvent - no order table found")	
	
	end

end

function orderTableEvent:calcProduct()

	local random = getRandomRange(0, self.chanceTotal)
	
	local counter = 0
	for index, value in ipairs(self.chances) do
		counter = counter + value
		
		if (random <= counter) then
			return self.pool[index]
			
		end
		
	end
	
	return "error"		

end

function orderTableEvent:onTick(time)

	if (scene:isStartingMovie() or scene:isPlayingMovie()) then
		return
	end

	if (not self.active) then
		return
	end

	if (self.timeUntilEnter > 0) then
		self.timeUntilEnter = self.timeUntilEnter - time
		if (self.timeUntilEnter <= 0) then
			qSequence(self.sequenceStart)
		
		end	
	end

	if (self.started == false) then
		return
	end
	
	if (self.completed == true) then
		return
	end
	
	if (self.state == "ordering") then
	
		self.timer1 = self.timer1 - time		
		if (self.timer1 < 0) then
			self.timer1 = 0
		end
		
		eventBar:setProgress(self.timer2/1000)
		self.pb:setProgress(self.timer2/self.timeUntilEnd)
		
		if (self.timer1 <= 0) then
		
			-- add a new order
			for i = 1, self.numProductsPerOrder do
				local prod = self:calcProduct()
				cout("product:" .. prod .. "\n")
				self.order:addProduct(prod)
			end
			
			-- increase order counter
			self.countOrders = self.countOrders + 1
			
			-- pop
			if (self.countOrders == 1) then
				self.order:setVisible(true)
				self.order:popIn()
				emily:playSound("SOUND_EVENT_ATTENTION")
			
			end
			
			-- reset timer
			self.timer1 = self.timeUntilNextOrder
	
		end
		
		-- handle end timer
		self.timer2 = self.timer2 - time

		-- handle state
		if (self.countOrders == self.numOrders or self.timer2 <= 0) then
			self.state = "waiting until end"
			cout("waiting until end\n")
		end
		
	elseif (self.state == "waiting until end") then

		self.timer2 = self.timer2 - time		
		if (self.timer2 < 0) then
			self.timer2 = 0
		end
		
		eventBar:setProgress(self.timer2/1000)
		self.pb:setProgress(self.timer2/self.timeUntilEnd)
		
		if (self.timer2 <= 0) then

			-- event failed
			self:onDone()
		
		end
		
	else
		
		-- do nothing	
			
	end	
	
end

function orderTableEvent:onStart()

	day:onNotify("start eating")

end

function orderTableEvent:onDone()

	day:onNotify("stop eating")
	day:onNotify("event done")

	-- check the order
	if (self.order:isCompleted()) then
		self.state = "win"
		emily:playSound(self.soundEventCompleteAll)		
        if (self.endScore > 0) then
            incScore(self.endScore, emily:getScreenX(), emily:getScreenY() + scorePersonFloaterOffsetY)
        end
	
	else
		self.state = "lose"
		
	end
	
	-- destroy it	
	self.order:setObsolete(true)
	self.order = nil
	
	-- destroy pb
	self.pb:setVisible(false)
	self.pb = nil
		
	-- done sequence
	if (self.state == "win" and self.sequenceWin) then
		qInsertSequence(self.sequenceWin)	
	
	elseif (self.sequenceLose) then
		qInsertSequence(self.sequenceLose)		
	end

	-- state
	self.completed = true	
	
	-- eventbar
	eventBar:animateToDeactive()

end

function orderTableEvent:onTaskHook(actorType, taskType, p0, p1)

	if ((self.started == true) and (self.completed ~= true)) then
		if (actorType == "emily") then
			if (taskType == "TableTask") then
				local gridX = emily:getPosition():getGridX()
				local gridY = emily:getPosition():getGridY()
				local workX = self.table:getWorkNode():getGridX()
				local workY = self.table:getWorkNode():getGridY()
							
				if ((gridX == workX) and (gridY == workY)) then

					-- deselect table
					self.table:setSelected(false)

					-- hand over products
					-- 200 is the MINIMAL_SERVE_DURATION; see TableTask.cpp
					insert()
					emily:qWait(200)
					emily:qCallback(self, self.handleDistibute)
					append()
					
					return false				
				end
			end
		end
	end	

	return false
end

function orderTableEvent:handleDistibute()
	n = tray:distributeProducts(self.order)
	if (n > 0) then	
		-- check start
		if (self.countHanded == 0) then
			self:onStart()		
		end
	
		-- update
		self.order:draw()	
		self.countHanded = self.countHanded + n
		
		-- check end
		if (self.state == "waiting until end") then
			if (self.order:isCompleted()) then
				self:onDone()								
			end
		end
		
		-- score
		if (self.score > 0) then
		    incScore(self.score * n, emily:getScreenX(), emily:getScreenY() + scorePersonFloaterOffsetY)
		end
		emily:playSound(self.soundEventCompleteOne)	
	end
end

function orderTableEvent:onNotify(notification)

	if (notification == "start") then
		self.started = true
	elseif (notification == "start ordering") then
		self.state = "ordering"
		self.timer1 = 0
		self.timer2 = self.timeUntilEnd
		self.pb:setVisible(true)
		eventBar:animateToActive()
		eventBar:raiseCurtain()		
	elseif (notification == "trigger start ordertable") then
		qSequence(self.sequenceStart)
	end
	
end
