
local Get = Object.GetProperty
local Set = Object.SetProperty
local Find = this.GetNearbyObjects
local Animation = { [1] = 0, [2] = 1, [3] = 2 }
local Frame = 1
local timeTot=0
local timePerUpdate=math.random(5,10)

function Create()
	Set(this,"HomeUID",me["id-uniqueId"])
	Set(this,"Ventilation","off")
	Set(this,"Tooltip","tooltip_VendingAirConditioner")
	Set(this,"SubType",0)
	if (this.Or.x==0 and this.Or.y==1) or (this.Or.x==0 and this.Or.y==-1) then
		Set(this,"Anim","on")
	else
		Set(this,"Anim","off")
	end
	newTimer = Object.Spawn("DoorTimer",this.Pos.x, this.Pos.y)
	Set(newTimer,"Tooltip","tooltip_VendingAirConditioner")
end

function enableVentilation()
	if this.Or.x==-1 then-- rotated once
		newWindow1 = Object.Spawn("Window",this.Pos.x,this.Pos.y-0.5)
		newWindow2 = Object.Spawn("Window",this.Pos.x,this.Pos.y)
		newWindow3 = Object.Spawn("Window",this.Pos.x,this.Pos.y+0.5)
	elseif this.Or.y==-1 then -- rotated twice
		newWindow1 = Object.Spawn("Window",this.Pos.x-0.5,this.Pos.y)
		newWindow2 = Object.Spawn("Window",this.Pos.x,this.Pos.y)
		newWindow3 = Object.Spawn("Window",this.Pos.x+0.5,this.Pos.y)
	elseif this.Or.x==1 then -- rotated three times
		newWindow1 = Object.Spawn("Window",this.Pos.x,this.Pos.y-0.5)
		newWindow2 = Object.Spawn("Window",this.Pos.x,this.Pos.y)
		newWindow3 = Object.Spawn("Window",this.Pos.x,this.Pos.y+0.5)
	else --placed down
		newWindow1 = Object.Spawn("Window",this.Pos.x-0.5,this.Pos.y)
		newWindow2 = Object.Spawn("Window",this.Pos.x,this.Pos.y)
		newWindow3 = Object.Spawn("Window",this.Pos.x+0.5,this.Pos.y)
	end
	Set(newWindow1,"HomeUID",this.HomeUID)
	Set(newWindow2,"HomeUID",this.HomeUID)
	Set(newWindow3,"HomeUID",this.HomeUID)
	newWindow1.Or.x = this.Or.x
	newWindow1.Or.y = this.Or.y	
	newWindow2.Or.x = this.Or.x
	newWindow2.Or.y = this.Or.y	
	newWindow3.Or.x = this.Or.x
	newWindow3.Or.y = this.Or.y
	Set(this,"Ventilation","on")
end

function disableVentilation()
	if newWindow1~=nil and newWindow2~=nil and newWindow3~=nil then
		newWindow1.Delete()
		newWindow2.Delete()
		newWindow3.Delete()
	else
		myWindows = Find("Window",2)
		for thatWindow, distance in pairs(myWindows) do
			if thatWindow.HomeUID==this.HomeUID then thatWindow.Delete() end
		end
		myWindows=nil
	end
	Set(this,"Ventilation","off")
end

function AnimateCooling()
	if this.Anim=="on" then
		this.SubType = Animation[Frame]
		Frame = Frame + 1
		if Frame > 3 then
			Frame = 1
		end
	end
end

function Update( timePassed )
	timeTot = timeTot + timePassed
	if timeTot>=timePerUpdate then
		timeTot=0
		local hasPower = ( this.Triggered or 0 ) > 0
		if hasPower then
			if Get(this,"Ventilation")=="off" then
				enableVentilation()
			end
			AnimateCooling()
			timePerUpdate=0.1
		else
			if Get(this,"Ventilation")=="on" then
				disableVentilation()
			end
			timePerUpdate=math.random(5,10)
		end
	end
end
