dofile("script/layouts/room_intro.lua")
dofile("script/shifts/intro_animations.lua")

levelDesc.name = "Intro"
levelDesc.allowSkipStory = false
levelDesc.layoutId = 0
levelDesc.areaId = 0
levelDesc.levelId = 1
levelDesc.isGamePlayLevel = false
levelDesc.targetScore = 9
levelDesc.music = "INTRO"
levelDesc.musicMood = "1"
levelDesc.dispatchEnabled = false
levelDesc.ambientLoop = "SND_INTRO_RAIN_LOOP"
levelDesc.heroDesc =
{
	name = "hero",
	base = "sarah",
	baseAnimation = "SARAH_WET",
	idleAnimations = "",
}

levelDesc.holdPressureReactionTime = 1000
levelDesc.holdPressureDuration = 10000
levelDesc.pumpReactionTime = 6000
levelDesc.numPumpTimes = 2
levelDesc.numPumpCycles = 3

function levelDesc:onShiftStartBegin()
	self.timerActive = false
	self:shiftStartEnd() -- Start shift without start shift dialog.
	self:handleTrigger("start intro")

	function runFlickerOptions(self, options)
		self.numFlickerTimes = self.numFlickerTimes or 0
		self.numFlickerTimes = self.numFlickerTimes - 1
		if (self.numFlickerTimes <= 0) then
			self.flickerOptionIdx = self.flickerOptionIdx or 0
			self.flickerOptionIdx = self.flickerOptionIdx + 1
			self.flickerOptionIdx = ((self.flickerOptionIdx - 1) % #options) + 1
			self.numFlickerTimes = options[self.flickerOptionIdx][1]
		end
		return options[self.flickerOptionIdx][2]
	end

	function pickFlickerOption(self, options)
		self.numFlickerTimes = self.numFlickerTimes or 0
		self.numFlickerTimes = self.numFlickerTimes - 1
		if (self.numFlickerTimes <= 0) then
			self.flickerOptionIdx = math.Random(#options)
			self.numFlickerTimes = options[self.flickerOptionIdx][1]
		end
		return options[self.flickerOptionIdx][2]
	end

	local s1 = self:getChild("rain")
	s1:doEvery(0, function()
		s1.frame = (s1.frame + 1) % s1.frameCount
		s1.x = math.Random(-16.5, 16.5)
		s1.y = math.Random(0, 8.5)
		s1.flipHorizontal = not s1.flipHorizontal
		return math.Random(80, 120)
	end)

	self:doEvery(20, function()
		local p
		p = self:getPointInMask("INTRO_RAINDROP_MASK")
		if (p) then
			local desc = {
				class = "SpriteExt",
				x = p.x,
				y = p.y,
				floor = -300,
				baseAnimation = "INTRO_RAINDROP",
				anchor = "center",
			}
			local drop = self:add(desc)
			drop:animate({{startFrame=0, frameTime=100}, {remove=true}})
		end

		p = self:getPointInMask("INTRO_RAINSPLASH_MASK")
		if (p) then
			local desc = {
				class = "SpriteExt",
				x = p.x,
				y = p.y,
				floor = 300,
				baseAnimation = "INTRO_RAINSPLASH",
				anchor = "bottom",
			}
			local drop = self:add(desc)
			drop:animate({{startFrame=0, frameTime=70}, {remove=true}})
		end
	end)

	local s2 = self:getChild("ambulance_orange_light")
	s2:doEvery(0, function()
		s2.visible = not s2.visible
		return runFlickerOptions(s2, {
			{1, 200},
			{1, 600},
		})
	end)

	local s3 = self:getChild("ambulance_red_light")
	s3.visible = false
	s3:doEvery(0, function()
		s3.visible = not s3.visible
		return runFlickerOptions(s3, {
			{1, 600},
			{1, 200},
		})
	end)

	local s4 = self:getChild("ambulance_red_side_light")
	s4:doEvery(200, function()
		s4.visible = not s4.visible
		return runFlickerOptions(s4, {
			{1, 200},
			{1, 600},
		})
	end)

	local s5 = self:getChild("motorbike_orange_light")
	s5:doEvery(0, function()
		s5.visible = not s5.visible
		return pickFlickerOption(s5, {
			{3, 100},
			{2, 300},
			{3, 50},
			{1, 2000},
		})
	end)

	local s7 = self:getChild("car_red_light")
	s7:doEvery(1000, function()
		s7.visible = not s7.visible
	end)
end

function levelDesc:checkRemoveComeOnPump(time, john)
	if (john and john.hideMessageDialog and self.comeOnPumpRemoveTime and self.comeOnPumpRemoveTime > 0) then
		self.comeOnPumpRemoveTime = self.comeOnPumpRemoveTime - time
		if (self.comeOnPumpRemoveTime <= 0) then
			john:hideMessageDialog("TEXT_INTRO_21")
		end
	end
end

function levelDesc:handleTrigger(trigger, meta)
	CareLevel.handleTrigger(self, trigger, meta)

	if (trigger == "start intro") then
		self:getChild("CLICK_CONTINUE"):setLocation(330, 690)
		self.heartBar = level:add({class="HealthSprite", x=327, y=588})
		self.heartBar.health = 0

--print("Intro started!")
		_G.john = self:getChild("john");
		self.droppedItemsNames = {
			"bandage",
			"desinfection",
			"needle_thread",
			"air_pump",
		}
		local bag = self:getChild("bag")
		bag.onClick = function()
--print("Clicked bag!")
			self.heartBar.overlayClipFraction = 0.20
			self:heartsToBar(1, bag.x + bag.width/2, bag.y, false)
			bag.clickable = false
			taskSystem:createAnimation("sarahDropsBag")
		end
		self.droppedItemIndex = 0
		taskSystem:createAnimation("sarahArrives")

	elseif (trigger == "bag dropped") then
		self:handleTrigger("next pickup item")

	elseif (trigger == "next pickup item") then
--print("Picked up an item!")
		local name = self.droppedItemsNames[self.droppedItemIndex]
		if (name) then
			local thing = self:getChild(name)
			self:addHeartScoreWithFloater(1, thing.x + thing.width/2, thing.y, false)
		end

		self.droppedItemIndex = self.droppedItemIndex + 1
		local name = self.droppedItemsNames[self.droppedItemIndex]
		if (name) then
--print("Find: "..name)
			self.heartBar.overlayClipFraction = 0.35
			local thing = self:getChild(name)
			thing.clickable = true
			thing.onClick = function()
--print("Found: "..name)
				thing.clickable = false
				taskSystem:createAnimation("pickupItem", {item=thing})
			end
			john:createOverhead("icon_"..name..":icons")
		else
--print("All items found")
			self.heartBar.overlayClipFraction = 0.60
			taskSystem:createAnimation("returnItems")
		end

	elseif (trigger == "start holding pressure") then
--print("Start holding pressure!")
		self.heartBar.overlayClipFraction = 1.00
		self.heartBar:animateWarning()
		taskSystem:createAnimation("holdPressure")

	elseif (trigger == "321 now") then
--print("321 now!")
		if (self.doSpawnPressureArrow) then
			taskSystem:createAnimation("spawnPressureArrow")
		end
		self.doSpawnPressureArrow = true
		self.reactionTime = self.holdPressureReactionTime
		self.holdDownTime = self.holdPressureDuration
		self.holdingDown = false
		self.waitingForTakeOver = true

		john.onClick = nil
		self.onMouseDown = function()
--print("Self mouse DOWN.\nReaction time = "..self.reactionTime.."\nHold time: "..self.holdDownTime)
			self.holdingDown = true
			if (self.waitingForTakeOver) then
--print("waitingForTakeOver")
				if (self.reactionTime > 0) then
--print("Mouse DOWN within reaction time")
					self.waitingForTakeOver = false
					self:heartsToBar(1, 322, 522, false)
					taskSystem:createAnimation("johnMovesToHead")
				end
			else
--print("John is at head: say 'Good!'")
				taskSystem:createAnimation("johnSaysGood")
				self.timerAnimation = "johnSaysGood2"
				self.messageTimer = 500
			end
		end

		self.onMouseUp = function()
--print("############ Level mouse UP.\nReaction time = "..self.reactionTime.."\nHold time: "..self.holdDownTime)
			self.holdingDown = false
			if (not self.waitingForTakeOver) then
				if (self.holdDownTime > 0) then
--print("############ Mouse UP within Hold Down time")
					taskSystem:createAnimation("johnSaysToKeepPressure")
					self.timerAnimation = "johnSaysToKeepPressure2"
					self.messageTimer = 500
				end
			end
		end

		john.onTick = function(_, time)
			john:tick(time)
			if (self.waitingForTakeOver) then
				if (self.reactionTime > 0) then
					self.reactionTime = self.reactionTime - time
					if (self.reactionTime <= 0) then
--print("Reaction time OVER")
						john.onTick = nil
						self.onMouseDown = nil
						self.onMouseUp = nil
						john.clickable = false
						taskSystem:createAnimation("holdPressureAgain")
					end
				end
			else
				if (self.holdingDown and self.holdDownTime > 0) then
					self.holdDownTime = self.holdDownTime - time
					if (self.holdDownTime <= 0) then
--print("Hold down time OVER")
						john.onTick = nil
						self.onMouseDown = function()
							-- A trick to not let the mouse-up click the message away:
							self.onMouseDown = nil
							self.onMouseUp = nil
						end
						self.onMouseUp = function()
							-- A trick to not let the mouse-up click the message away:
							self.onMouseDown = nil
							self.onMouseUp = nil
							return true -- handled, so it cancelles the message's click
						end
						self.messageTimer = nil
						self.timerAnimation = nil

						self.heartBar.health = -1 -- You broke his heart, aw....
						john.clickable = false
						taskSystem:createAnimation("heartStopped")
					end
				end
			end

			if (isNumber(self.messageTimer) and isString(self.timerAnimation) and self.messageTimer > 0) then
				self.messageTimer = self.messageTimer - time
				if (self.messageTimer <= 0) then
					taskSystem:createAnimation(self.timerAnimation)
					self.messageTimer = nil
					self.timerAnimation = nil
				end
			end
		end

	elseif (trigger == "start bandaging") then
		john.clickable = false
		taskSystem:createAnimation("johnSaysGood")

	elseif (trigger == "hold again") then
		taskSystem:createAnimation("holdPressure")

	elseif (trigger == "start pumping") then
--print("Start pumping!")
		self.pumpTimes = 0
		self.mouseIsDown = false
		self.pumpCycles = 0
		john.clickable = false
		taskSystem:createAnimation("startPumping")

	elseif (trigger == "must pump") then
--print("Pump!")
		self.onMouseDown = function()
			self.onMouseDown = nil
			self.mouseIsDown = true
			self.reactionTime = -1
			taskSystem:createAnimation("sarahPumpsIn")
		end
		self.onMouseUp = function()
--print("Mouse up on John")
			self.pumpTimes = self.pumpTimes + 1
			self.mouseIsDown = false
			self.onMouseDown = nil
			self.onMouseUp = nil
			if (self.pumpTimes < self.numPumpTimes) then
--print("Pumped once")
				self.reactionTime = self.pumpReactionTime
			else
--print("Pumped twice")
				self.heartBar:addOneFlyingHeart({x=320, y=530})
				self.heartBar:animateHealthBackground()
				john.onTick = nil
				self.reactionTime = -1
			end
			john.clickable = false
			taskSystem:createAnimation("sarahPumpsOut")
		end
		self.reactionTime = self.pumpReactionTime
		john.onTick = function(_, time)
			john:tick(time)
			self:checkRemoveComeOnPump(time, john)
			if (not self.mouseIsDown and self.reactionTime > 0) then
				self.reactionTime = self.reactionTime - time
				if (self.reactionTime <= 0) then
					taskSystem:createAnimation("comeOnPump")
					self.comeOnPumpRemoveTime = 2400
					self.reactionTime = self.pumpReactionTime
				end
			end
		end

	elseif (trigger == "sarah pumped") then
--print("Allison pumped!\nCycles: "..self.pumpCycles)
		if (self.pumpTimes >= self.numPumpTimes) then
--print("Pumped twice")
			self.pumpTimes = 0
			self.pumpCycles = self.pumpCycles + 1

			if (self.pumpCycles >= self.numPumpCycles) then
--print("Patient saved")
				self:heartsToBar(3, 327, 558, false)
				self.heartBar:animate({alpha=0, duration=800})
				john.comeOnPumpRemoveTime = nil
				taskSystem:cancelAllTasksFor(john)
				john.clickable = false
				taskSystem:createAnimation("patientSaved")
				player.trophyManager:awardTrophy(21, 1)
				self.onMouseDown = nil
				self.onMouseUp = nil
	        else
--print("Another pumping cycle")
				john.clickable = false
				taskSystem:createAnimation("startPumping")
			end
		else
--print("Another pump")
			self:handleTrigger("must pump")
		end

	elseif (trigger == "patient saved") then
--print("Patient saved!")
       self:onLevelEndContinue()

	end
end
