dofile("script/layouts/entrance_hall.lua")

RoomDialog = deriveLuaClass("RoomDialog", "DialogCare")

levelDesc.name = "Selection Scene"
levelDesc.levelId = 100
levelDesc.areaId = 0
levelDesc.isGamePlayLevel = false
levelDesc.autoStartShift = false
levelDesc.music = "SELECTION"
levelDesc.musicMood = ""
levelDesc.heroDesc =
{
	name = "hero",
	base = "sarah",
	x = 450,
	y = 1000,
}

levelDesc.doctorPositions = {
	{ off={x=312, y=410}, on={x=312, y=450}, un={x=312, y=351} },
	{ off={x=412, y=410}, on={x=412, y=470}, un={x=412, y=371} },
	{ off={x=512, y=410}, on={x=512, y=470}, un={x=512, y=371} },
	{ off={x=612, y=410}, on={x=612, y=470}, un={x=612, y=371} },
	{ off={x=712, y=410}, on={x=712, y=450}, un={x=712, y=351} },
}

levelDesc.actionPositions = {
	{x=43, y=319},
	{x=130, y=300},
	{x=254, y=287},
	{x=168, y=354},
	{x=357, y=554},
	{x=298, y=604},
	{x=45, y=689},
	{x=150, y=697},
	{x=258, y=680},
	{x=366, y=660},
	{x=447, y=581},
	{x=619, y=577},
	{x=670, y=531},
	{x=691, y=604},
	{x=688, y=699},
	{x=777, y=702},
	{x=896, y=707},
	{x=984, y=704},
	{x=752, y=359},
	{x=757, y=267},
	{x=843, y=309},
	{x=940, y=370},
	{x=975, y=229},
}

levelDesc.waitAreaPositions = {
	{x=357, y=554},
	{x=298, y=604},
	{x=45, y=689},
	{x=150, y=697},
	{x=258, y=680},
	{x=366, y=660},
	{x=447, y=581},
	{x=619, y=577},
	{x=670, y=531},
	{x=691, y=604},
	{x=688, y=699},
	{x=777, y=702},
	{x=896, y=707},
	{x=984, y=704},
}

levelDesc.deskPositions = {
	{x=404, y=394},
	{x=471, y=409},
	{x=487, y=392},
	{x=539, y=408},
	{x=559, y=392},
	{x=604, y=402},
}

levelDesc.entrancePositions = {
	{x=361, y=1000},
	{x=400, y=1000},
	{x=450, y=1000},
	{x=500, y=1000},
	{x=550, y=1000},
	{x=600, y=1000},
	{x=649, y=1000},
}

levelDesc.hallwayPositions = {
	-- Left hallway
	{x=-80, y=200},
	{x=-80, y=240},
	{x=-80, y=280},
	{x=-80, y=320},
	{x=-80, y=360},
	{x=-80, y=400},

	-- Right hallway
	{x=1100, y=200},
	{x=1100, y=240},
	{x=1100, y=280},
	{x=1100, y=320},
	{x=1100, y=360},
	{x=1100, y=400},
}

function levelDesc:onInitialized()
	self.class.onInitialized(self)
	self:setSpecialState()

	if (isDebug) then
		for _,t in pairs({self.actionPositions, self.waitAreaPositions, self.deskPositions, self.entrancePositions, self.hallwayPositions}) do
			for _,p in pairs(t) do
				if (not self:canWalkTo(p)) then
					print("A non-walkable position has been entered! {x="..tostring(p.x)..", y="..tostring(p.y).."}")
				end
			end
		end
	end

	scene:getChild("PLAY").onClick = function()
		self.clickedPlay = true
		scene:getChild("PLAY").enabled = false
		self.lisa:addTask({class="SetTask", playIdleAnimations=false})
		self.lisa:addTask({class="Task", duration=400})
		self.lisa:addTask({class="CallTask", func=function() self.lisa:hideMessageDialog("WELCOME") end, object=self})
		self.lisa:addTask({class="Task", duration=800})
		self.lisa:addTask({class="PlayAnimationTask", animation="YELL", whenFinished="stay", wait=false})
		self.lisa:addTask({class="MessageTask", textId="SEL_YELL_COME", keepOpen=true})
		self.lisa:addTask({class="Task", duration=500})
		self.lisa:addTask({class="CallTask", func=function() self:doctorsWalkToDesk(true) end})
		self.lisa:addTask({class="Task", duration=4000-500})
		self.lisa:addTask({class="RemoveMessageTask", textId="SEL_YELL_COME"})
		self.lisa:addTask({class="PlayAnimationTask", animation="IDLE", whenFinished="stay", wait=false})
		self.lisa:addTask({class="MessageTask", textId="SEL_YELL_CLICK_TO_START", keepOpen=true})
		self.lisa:addTask({class="SetTask", playIdleAnimations=true})
	end

	scene:getChild("SETTINGS").onClick = function()
		scene:openDialog(scene:createDialog("DIALOG_SETTINGS"))
	end

	scene:getChild("TROPHIES").onClick = function()
		scene:getChild("TROPHIES").enabled = false
		hero:addTask({class="WalkToTask", target={x=-100,y=330}})
		hero:addTask({class="CallTask", func=function() 
			ghf.setTransition("defaultTransition")
			ghf.gotoScene(ghf.createScene("trophy"))
		end})
	end

	scene:getChild("QUIT").onClick = ghf.showQuitMessage

	hero.groupPos = {x=503, y=655}
	hero:addTask({class="WalkToTask", target=hero.groupPos})

	self.doctors = {
		{ base="john", x=-1000 },
		{ base="ruth", x=-1000 },
		{ base="connor", x=-1000 },
		{ base="robin", x=-1000 },
		{ base="chance", x=-1000 },
	}

	for room,v in ipairs(self.doctors) do
		local doc = self:createCharacter(v)
		self.doctors[room] = doc
		doc.room = room
		doc.on = player and (room == player.unlockedRoom)
		doc.isDoctor = true

		doc.onStoryComplete = function() self:newDoctorStory(doc) end
		self:initActionPerson(doc)
		self:newDoctorStory(doc)

		doc.onClick = function()
			if (player and room <= player.unlockedRoom) then
				doc.clickable = false
				if (not doc.on) then
					for _,d in ipairs(self.doctors) do
						d.on = false
					end
					doc.on = true
					self:doctorsWalkToDesk(false)
					local pos = self.doctorPositions[room].on
					doc:addTask({class="WalkToTask", target=pos})
					doc:addTask({class="Task", duration=300})
				end
				doc:addTask({class="CallTask", func = function()
					player:setRoomIdAndFile(doc.room)
					scene:openDialog(scene:createDialog("room_details"))
					self:updateDoctorsClickable()
				end})
			end
		end
	end

	local maleNurse = self:createCharacter({base="male_nurse"})
	local femaleNurse = self:createCharacter({base="female_nurse"})
	local janitor = self:createCharacter({base="janitor"})
	
	janitor.clickable = true
	janitor.drawOutline = false
	janitor.onClick = function()
		if (not self.clickedPlay) then
			taskSystem:cancelAllTasksFor(janitor)
			if (janitor.trophyRight) then
				janitor:playAnimation("TROPHY#RIGHT", 1)
			else
				janitor:playAnimation("TROPHY#LEFT", 1)
			end
			janitor.trophyRight = not (janitor.trophyRight or false)
			player.trophyManager:awardTrophy(28, 1)
		end
	end
	
	self:initActionPerson(maleNurse, true)
	self:initActionPerson(femaleNurse, true)
	self:initActionPerson(janitor, true)
	self:newNurseStory(maleNurse)
	self:newNurseStory(femaleNurse)
	self:newJanitorStory(janitor)
	maleNurse.onStoryComplete = function(nurse) self:newNurseStory(nurse) end
	femaleNurse.onStoryComplete = maleNurse.onStoryComplete
	janitor.onStoryComplete = function() self:newJanitorStory(janitor) end
	maleNurse.newActionDelay = math.Random(1000, 8000)
	femaleNurse.newActionDelay = math.Random(1000, 8000)
	janitor.newActionDelay = math.Random(1000, 8000)

	self.npcs = {
		maleNurse,
		femaleNurse,
		janitor,
	}

	self.lisa = self:createCharacter({ base="lisa", x=470, y=320 })
	self.lisa.onMessageClick = function()
		scene:openDialog(scene:createDialog("DIALOG_PLAYERSELECT"))
	end

	self.chairs = {
		self:getObject("chair_left1"),
		self:getObject("chair_left2"),
		self:getObject("chair_right1"),
		self:getObject("chair_right2"),
	}

	self.numPatientTypes = 0
	self.patientTypeTable = {}
	for k,v in pairs(self.characterTypes) do
		if (k ~= "default" and v.isPatient) then
			self.patientTypeTable[self.numPatientTypes] = v
			self.numPatientTypes = self.numPatientTypes + 1
		end
	end

	self.patients = {}

	for i=1,3 do
		self:createNewPatient(false)
	end
end

function levelDesc:updateDoctorsClickable()
	for _,doc in ipairs(self.doctors) do
		doc.clickable = (doc.room <= player.unlockedRoom)
	end
end

function levelDesc:doctorsWalkToDesk(firstTime)
	self.doctorsCalled = true
	for room,doc in ipairs(self.doctors) do
		local docPos = self.doctorPositions[room]
		taskSystem:cancelAllTasksFor(doc)

		doc.clickable = false
		local available = (doc.room <= player.unlockedRoom)

		doc.old_baseAnimation = doc.old_baseAnimation or doc.baseAnimation
		if (firstTime) then
			if (room ~= 4 and room ~= 5) then -- Robin and Chance don't have "RUN" animations.
				doc.baseAnimation = doc.old_baseAnimation.."_RUN"
			end
			doc.valueMultipliers.walkSpeed = nil
			doc.walkSpeed = 400
		end

		if (available) then
			doc:addTask({class="WalkToTask", target=docPos.off})
		elseif (firstTime) then
			doc:addTask({class="WalkToTask", target=docPos.un})
		end

		doc:addTask({class="SetTask", baseAnimation=doc.old_baseAnimation, walkSpeed=100, animation=""})
		if (firstTime) then
			if (doc.on) then
				doc:addTask({class="Task", duration=100})
				doc:addTask({class="WalkToTask", target=docPos.on})
				doc:addTask({class="CallTask", func=function() self:updateDoctorsClickable() end})
			end
		end

		if (available) then
			doc:addTask({class="SetTask", direction="down"})
		else
			doc:addTask({class="SetTask", direction="up"})
			doc.playIdleAnimations = false
		end
	end

	if (firstTime) then
		local skipCharacters = table.copy(self.doctors)
		table.insert(skipCharacters, self.lisa)
		table.insert(skipCharacters, hero)
		table.insert(skipCharacters, level:getObject("guineapig"))

		local characters = level:getCharacters()
		for _,v in ipairs(characters) do
			if (not table.contains(skipCharacters, v)) then
				taskSystem:cancelAllTasksFor(v)
				local exitPos
				if (v.y > 500) then
					exitPos = self.entrancePositions
				elseif (v.x < 512) then
					exitPos = self.hallwayPositions -- TODO: Left or right hallway
				else
					exitPos = self.hallwayPositions -- TODO: Left or right hallway
				end
				v:addTask({class="WalkToTask", target=exitPos[math.Random(table.icount(exitPos))]})
				v:addTask({class="CallTask", func=function() self:removeStoryPerson(v) end})
			end
		end

		self.patients = {}
		self.npcs = {}
	end
end

function levelDesc:onPlayerSwitch(switching)
	if (self.doctorsCalled) then
		for _,doc in ipairs(self.doctors) do
			self.doctorsCalled = false
			doc.newActionDelay = 0
			self:newDoctorStory(doc)
		end
	end
	self:lisaShowChangePlayerMessage()
    scene:getChild("PLAY").enabled = true

    if (switching and not player:hasUnlockedSomething()) then
		player:setLevelIdAndFile(1);
		ghf.gotoScene(ghf.createScene("game"));
    end
end

function levelDesc:onTick(time)
	self:tick(time)

	for _,v in ipairs(self.patients) do
		self:updateStoryFor(v, time)
	end

	if (not self.doctorsCalled) then
		for _,v in ipairs(self.doctors) do
			self:updateStoryFor(v, time)
		end
	end

	for _,v in ipairs(self.npcs) do
		self:updateStoryFor(v, time)
	end

end

-- ###########################################################################################
-- Selection scene mini-stories
-- ###########################################################################################
function levelDesc:lisaShowChangePlayerMessage()
    local welcomeText = string.format(ghf.getString("SEL_WELCOME"), player.name)

    local desc = { class="BalloonDialog",
		owner = self.lisa,
		dialogId = "WELCOME",
		anchor = "top",
		topPadding = 20,
		sidePadding = 20,
		bottomPadding = 20,
		tipType = "point",
		tipSide = "center",
		children = {
			{ class="Label",
				name="message",
				text = welcomeText,
				y = 10,
				maxWidth=300,
				wrapStyle="truncate",
				font="FONT_WELCOME:default",
				anchor="top",
				roundPos=false,
			},
		},
		content = {
			children = {
				{ class="Button", name="ok", y=25, image="BUTTON_CHANGENAME:sceneselection", anchor="top", },
			},
		},
		offset = {x=0, y=5},
		forcedHeight = 100,
	}

	local dlg = self.lisa:newChild(desc)
	self.lisa:setupBalloonDialog(dlg, desc)
end

function levelDesc:createNewPatient(initialPosition)
	local patient = self.patientTypeTable[math.Random(self.numPatientTypes)]
	patient = self:spawnPatient(patient, false)
	patient.onStoryComplete = function()
		self:createNewPatient(patient.actionPos)
		self:removeStoryPerson(patient)
		table.remove(self.patients, person)
	end
	patient.dropHealth = false
	patient.inHospitalClothes = (math.Random(1000) > 500)
	patient.health = randomFromWeightedTable({
		{weight=300, health="healthy"},
		{weight=300, health="cured"},
		{weight=300, health="feelingbetter"},
		--{weight=300, health="sick"},			-- Not all animations available.
		--{weight=300, health="seriouslysick"},	-- Not all animations available.
	}).health

	table.insert(self.patients, patient)
	self:initActionPerson(patient, initialPosition)
	self:newPatientStory(patient)
end

function levelDesc:initActionPerson(person, initialPosition)
	person.newActionDelay = math.Random(2000, 20000)
	person.actionLock = 0

	person.valueMultipliers = person.valueMultipliers or {}
	person.valueMultipliers.walkSpeed = 0.7

	if (not isTable(initialPosition)) then
		initialPosition = (initialPosition == nil and math.Random(1000) < 500) or initialPosition
		if (initialPosition) then
			initialPosition = self:getFreePosition(self.actionPositions)
		else
			initialPosition = self:getFreePosition(self.entrancePositions, false)
		end
	end
	if (isTable(initialPosition)) then
		person.actionPos = initialPosition
		person.location = initialPosition
	end
end

function levelDesc:newDoctorStory(doc)
	doc.story = randomFromWeightedTable({
		{weight=300, {a="walk"}, {a="hallway"}},
		{weight=200, {a="walk"}, {a="desk"}, {a="hallway"}},
		{weight=200, {a="desk"}, {a="hallway"}},
		{weight=50, {a="desk"}, {a="walk"}, {a="hallway"}},
		--{weight=300, {a="talk"}}, -- Not implemented yet!
	})
	doc.story = table.copy(doc.story)
	doc.story.weight = nil
end

function levelDesc:newPatientStory(patient)
	patient.story = randomFromWeightedTable({
		{weight=300, {a="desk"}, {a="sit"}, {a="doc"}, {a="hallway"}, {a="nodoc"}, {a="desk"}, {a="exit"}},
		{weight=300, {a="sit"}, {a="doc"}, {a="hallway"}, {a="nodoc"}, {a="exit"}},
		{weight=300, {a="desk"}, {a="doc"}, {a="hallway"}, {a="nodoc"}, {a="desk"}, {a="exit"}},
		{weight=300, {a="desk"}, {a="hallway"}, {a="desk"}, {a="exit"}},
		{weight=300, {a="hallway"}, {a="exit"}},
		{weight=300, {a="desk"}, {a="sit"}, {a="doc"}, {a="hallway"}, {a="nodoc"}},
		{weight=300, {a="sit"}, {a="doc"}, {a="hallway"}, {a="nodoc"}},
		{weight=300, {a="desk"}, {a="doc"}, {a="hallway"}, {a="nodoc"}},
		{weight=300, {a="desk"}, {a="hallway"}},
		{weight=300, {a="hallway"}},
	})
	patient.story = table.copy(patient.story)
	patient.story.weight = nil
end

function levelDesc:newNurseStory(nurse)
	nurse.story = randomFromWeightedTable({
		{weight=300, {a="desk"}, {a="hallway"}},
		{weight=300, {a="hallway"}},
	})
	nurse.story = table.copy(nurse.story)
	nurse.story.weight = nil
end

function levelDesc:newJanitorStory(janitor)
	janitor.story = randomFromWeightedTable({
		{weight=300, {a="walk", delay=0}, {a="anim"}},
		{weight=300, {a="walk"}},
		{weight=300, {a="anim"}},
		{weight=200, {a="hallway"}},
	})
	janitor.story = table.copy(janitor.story)
	janitor.story.weight = nil

	for _,v in ipairs(janitor.story) do
		if (v.a == "anim") then
			v.anim = "IDLE_XXX"
			v.cycles = math.Random(1, 4)
			v.frameTime = 160
		end
	end
end

function levelDesc:onStoryStepComplete(person)
	if (person.actionLock == 0) then
		person.newActionDelay = math.Random(person.minActionDelay, person.maxActionDelay)
		table.remove_at(person.story, 1)

		if (table.iempty(person.story)) then
			person:onStoryComplete()
		end
	end
end

function levelDesc:removeStoryPerson(person)
	self:releaseDoctor(person)
	self:releaseChair(person)
	person:remove()
end

function levelDesc:releaseDoctor(person)
	if (person.doc) then
		person.doc.playIdleAnimations = true
		person.doc.person = nil
		person.docDoingAction = false
		person.doc = nil
	end
end

function levelDesc:releaseChair(person)
	if (person.chair) then
		person.chair.actionOccupied = nil
		person.chair = nil
	end
end

function levelDesc:updateStoryFor(person, time)
	if (person.person or
		person.actionLock > 0 or
		not person.story or
		table.iempty(person.story)) then
		return
	end

	person.newActionDelay = (person.newActionDelay or 0) - time
	if (person.newActionDelay > 0) then
		return
	end

	local storyStep = person.story[1]
	local action = storyStep.a

	local minDelay = storyStep.minDelay or storyStep.delay
	local maxDelay = storyStep.maxDelay or storyStep.delay

	local success = false
	if (action == "desk") then
		success = self:goToDesk(person)
		minDelay = minDelay or 1000
		maxDelay = maxDelay or 3000

	elseif (action == "sit") then
		success = self:goToWaitArea(person)
		minDelay = minDelay or 1000
		maxDelay = maxDelay or 3000

	elseif (action == "walk") then
		success = self:goToPosition(person, self.actionPositions)
		minDelay = minDelay or 1000
		maxDelay = maxDelay or 3000

	elseif (action == "doc") then
		success = self:makeDoctorComeTo(person)
		minDelay = minDelay or 500
		maxDelay = maxDelay or 1000

	elseif (action == "nodoc") then
		self:releaseDoctor(person)
		success = true

	elseif (action == "hallway") then
		success = self:goToHallway(person)

	elseif (action == "exit") then
		success = self:goToPosition(person, self.entrancePositions)

	elseif (action == "anim") then
		local anim = storyStep.anim or ""
		local cycles = storyStep.cycles or -1
		local frameTime = storyStep.frameTime
		local whenFinished = storyStep.whenFinished or "default"
		person:addTask({
			class="PlayAnimationTask",
			animation=anim,
			cycles=cycles,
			frameTime=frameTime,
			whenFinished=whenFinished,
			wait=true,
		})
		success = true

	end

	person.minActionDelay = minDelay or 2000
	person.maxActionDelay = maxDelay or 20000

	if (success) then
		if (action ~= "sit") then
			self:releaseChair(person)
		end

		person.actionLock = person.actionLock + 1
		person:addTask({class="CallTask", func=function()
			person.actionLock = person.actionLock - 1
			self:onStoryStepComplete(person)
		end})

		if (person.doc) then
		person.actionLock = person.actionLock + 1
			person.doc:addTask({class="CallTask", func=function()
				person.actionLock = person.actionLock - 1
				self:onStoryStepComplete(person)
			end})
		end

		if (action == "doc") then
			person:addTask({class="Task", duration=1000})
		end
	else
		person.newActionDelay = math.Random(800, 1200)
	end
end

function levelDesc:goToWaitArea(person)
	-- Try a chair
	local tmpChairs = table.copy(self.chairs)
	while (not table.empty(tmpChairs)) do
		local chair = tmpChairs[math.Random(table.count(tmpChairs))]
		if (not chair.actionOccupied) then
			chair.actionOccupied = person
			person.chair = chair

			person:addTask({class="WalkToTask", target=chair})
			person:addTask({class="PlayAnimationTask", animation=chair.stationAnimation, cycles=-1, whenFinished="stay", frameTime=self.stationAnimationFrameTime})
			person.actionPos = chair.actionPos or chair.workPos or chair.location
			return true
		end
		table.remove_at(tmpChairs, chairIdx)
	end

	-- Try a wait pos
	local pos = self:getFreePosition(self.waitAreaPositions)	
	if (pos) then
		person:addTask({class="WalkToTask", target=pos})
		person.actionPos = pos
		return true
	end
end

function levelDesc:goToDesk(person)
	if (not self.doctorsCalled) then
		local pos = self:goToPosition(person, self.deskPositions)
		if (pos) then
			person:addTask({class="SetTask", direction="up"})
			return true
		end
	end
end

function levelDesc:goToHallway(person)
	local pos = self:goToPosition(person, self.hallwayPositions, false)
	if (pos) then
		if (person.doc) then
			person.doc:addTask({class="WalkToTask", target=pos})
			person.doc.actionPos = pos
		end
		return true
	end
end

function levelDesc:goToPosition(person, positions, skips)
	positions = positions or person.positions
	local pos = self:getFreePosition(positions, skips)
	if (pos) then
		person:addTask({class="WalkToTask", target=pos})
		person.actionPos = pos
		return pos
	end
end

function levelDesc:makeDoctorComeTo(person)
	if (self.doctorsCalled) then
		return true
	end

	local allCharacters = self:getCharacters()
	local docs = table.copy(self.doctors)
	while (not table.empty(docs)) do
		local doc = docs[math.Random(#docs)]
		if (not doc.person and doc.actionLock == 0) then
			local pos = self:getPositionNear(person, {{x=0, y=30}}, {doc}, 20, allCharacters)
			if (pos) then
				doc.playIdleAnimations = false
				doc.person = person
				person.doc = doc
				doc:addTask({class="WalkToTask", target=pos})
				doc:addTask({class="PlayAnimationTask", animation="COME_PATIENT", frameTime=180, cycles=2, whenFinished="stay"})
				doc.actionPos = pos
				return true
			end
		end
		table.remove(docs, doc)
	end
end

function levelDesc:getFreePosition(positions, skips, dist, allCharacters)
	allCharacters = allCharacters or self:getCharacters()
	positions = table.copy(positions)
	while (#positions ~= 0) do
		local idx = math.Random(#positions)
		local pos = positions[idx]
		if (skips == false or (not self:isSomeoneNear(pos, skips, dist, allCharacters))) then
			return pos
		end
		table.remove_at(positions, idx)
	end
end

function levelDesc:isSomeoneNear(pos, skips, dist, allCharacters)
	dist = dist or 80
	dist = dist * dist

	allCharacters = allCharacters or self:getCharacters()
	for _,v in ipairs(allCharacters) do
		if ((not table.contains(skips, v)) and v.actionPos) then
			local d = {x=v.actionPos.x - pos.x, y=v.actionPos.y - pos.y}
			if (d.x*d.x + d.y*d.y <= dist) then
				return true
			end
		end
	end
end

function levelDesc:getPositionNear(person, offsets, skips, dist, allCharacters)
	allCharacters = allCharacters or self:getCharacters()
	skips = (skips and table.copy(skips)) or {}
	offsets = offsets or {{100,0},{-100,0}}
	table.insert(skips, walker)
	local pos = person.actionPos or person.location
	for _,v in ipairs(offsets) do
		local newPos = {x=pos.x + v.x, y=pos.y + v.y}
		if ((skips == false) or (not self:isSomeoneNear(newPos, skips, dist, allCharacters))) then
			newPos.direction = v.direction
			return newPos
		end
	end
end

-- ###########################################################################################
-- RoomDialog
-- ###########################################################################################
function RoomDialog:onShow()
	local room = player.room
	local maxShift = player:getMaxShift(room)

	self:getChild("ROOM").text = string.format(ghf.getString("SEL_ROOM_FORMAT"), room, ghf.getString("SEL_ROOM"..room.."_NAME"))
	self:getChild("PREVIEW").image = "ROOM"..room.."_PREVIEW:sceneselection"
	self:getChild("DOC").image = "ROOM"..room.."_DOCTOR:sceneselection"

	self:getChild("BACK").onClick = function()
		self:close()
	end

	self:getChild("DECORATE").onClick = function()
		self:close()
		ghf.setTransition("defaultTransition");
		level:enterShop(self, room, player.shift);
	end

	local goPlay = function()
		self:close()
		scene:getChild("TROPHIES").enabled = false
	
		local doc = level.doctors[room]
		doc.playIdleAnimations = false
		doc.walkSpeed = hero.walkSpeed
		doc:addTask({class="Task", duration=300})
		doc:addTask({class="MessageTask", duration=2000, textId="SEL_LETS_GO_"..doc.profileKind})
		doc:addTask({class="WalkToTask", target={x=-100,y=290}})
		doc:addTask({class="CallTask", func = function()
			ghf.setTransition("defaultTransition");
			ghf.gotoScene(ghf.createScene("game"));
		end})
		for room,v in ipairs(level.doctors) do
			level.doctors[room].clickable = false
		end

		hero:addTask({class="Task", duration=300+2000-200})
		hero:addTask({class="WalkToTask", target={x=-100,y=330}})
	end

	self:getChild("PLAY").onClick = goPlay

	local boxNode = self:getChild("BOXES")

	self.boxes = {}
	for i=1,player.shiftCount do
		local box = self:newChild({
			class = "Switch",
			image = "SHIFT_BOX"..i..":sceneselection",
			x = boxNode.x + 80*(i-3), y = boxNode.y,
			enabled = (i <= maxShift),
			tag = i,
			group = 678,
			anchor="top",
			checked = (i == player.shift),
		})

		box.onClick = function()
			if (box.tag == player.shift) then
				goPlay()
			else
				player:setShiftIdAndFile(room, box.tag)
				self:updateStats(room, box.tag)
			end
		end

		local expertScore = level.targetScores[room][i].expert
		if (player:getShiftStats(room, i).highestHeartScore >= expertScore) then
			self:newChild({
				class = "Sprite",
				image = "SHIFT_EXPERT:sceneselection",
				x = box.x + 27, y = box.y + 61, anchor = "center",
				tooltip = "TOOLTIP_EXPERT",
			})
		end

		self.boxes[i] = box
	end

	self:updateStats(room, player.shift)
end

function RoomDialog:updateStats(room, shift)
	local stats = player:getShiftStats(room, shift)

	if (stats.highestHeartScore >= 0) then
		self:getChild("HEARTS").text = tostring(stats.highestHeartScore)
	else
		self:getChild("HEARTS").text = "-"
	end

	if (stats.minigameGrade >= 0) then
		self:getChild("MINIGAME").text = ghf.getString("SEL_ROOM_GRADE"..(7 - stats.minigameGrade))
	else
		self:getChild("MINIGAME").text = "-"
	end

	self:getChild("GUINEAPIG").textID = (stats.foundGuineaPig and "SEL_ROOM_FOUND") or "SEL_ROOM_NOT_FOUND"

	local specialCount = player:getSpecialItemCount(room, shift)
	local specialVal = self:getChild("SPECIAL")
	if (specialCount > 0) then
		specialVal.text = ghf.getString("SEL_ROOM_SPECIAL_FMT")
			:format(player:getSpecialItemPoints(room, shift), specialCount)
	else
		specialVal.text = "-"
	end
end
