Scriptname _00E_RentRoomScript extends Actor  Conditional
{script for anyone who rents a room}

ObjectReference Property Bed  Auto  
{bed to rent}

ObjectReference Property RoomDoor Auto
{door to unlock}

Worldspace Property Akropolis Auto

MiscObject Property Gold001 Auto

Actor Property PlayerREF Auto

bool DoorHasToClean

; rent room or clear rental
function RentRoom(int iGoldvalue)
	RegisterForSingleUpdateGameTime(24.0)

	; used to conditionalize innkeeper dialogue
	SetActorValue("Variable09", 1.0)
	If PlayerREF == None
		PlayerREF = Game.GetPlayer()
	EndIf
	Bed.SetActorOwner(PlayerREF.GetActorBase())
	PlayerREF.RemoveItem(Gold001, iGoldvalue)

	RoomDoor.Lock(False)
	RoomDoor.SetOpen(true)
	DoorHasToClean = False
endFunction

function ClearRoom()
; 	debug.trace(self + " ClearRoom called on RentRoomScript - room rental expired")
	; clear ownership - either rental expired or I died
	Bed.SetActorOwner((self as Actor).GetActorBase())
	UnregisterForUpdateGameTime()
	; used to conditionalize innkeeper dialogue
	SetActorValue("Variable09", 0.0)
	ClearRoomDoor()
endFunction

; Wait for the player to leave the inn and the meditation cell (he/she could be meditating in the inn)
; After that the door is free to be locked.
function ClearRoomDoor()
	Cell playerCell = PlayerREF.GetParentCell()
	Worldspace playerWorldspace = PlayerREF.GetWorldSpace()
	if playerCell != GetParentCell() && playerWorldspace != Akropolis
		DoorHasToClean = true
	else
		RegisterForSingleUpdate(5.0)
	endIf
endFunction

Event OnUpdate()
	; The room has been rented again between updates?
	If GetActorValue("Variable09") > 0.0
		Return
	EndIf

	ClearRoomDoor()
endEvent

; when this is called, reset the ownership on the bed
event OnUpdateGameTime()
	ClearRoom()
endEvent

; if I die, clear the room rental as well, to stop the timer
Event OnDeath(Actor akKiller)
	ClearRoom()
endEvent

function LockRoomDoor()
	if DoorHasToClean == true
		DoorHasToClean = false
		RoomDoor.Lock(True)
	endif
endFunction

Event OnCellAttach()
	If RoomDoor.Is3DLoaded()
		LockRoomDoor()	
	EndIf
EndEvent

Event OnCellLoad()
	LockRoomDoor()
EndEvent