import org.openhab.core.library.types.*

var Number counter = 1

rule Startup
when 
	System started
then
	say("Welcome at openHab!")
end

rule Goodbye
when 
	System shuts down
then
	say("Good bye!")
end

rule "Crontest"
	when 
		Time cron "0/15/30/45 * * * * ?"
	then
		say(counter)
		counter = counter + 1
end	

/**
 * This is a demo rule which simulates a real dimmer by reacting to increase/decrease commands 
 * and posting an updated state on the bus 
 */
rule "Dimmed Light"
	when
		Item DimmedLight received command
	then
		var Number percent = 0
		if(DimmedLight.state instanceof DecimalType) percent = DimmedLight.state as DecimalType 
			
		if(receivedCommand==INCREASE) percent = percent + 5
		if(receivedCommand==DECREASE) percent = percent - 5

		if(percent<0)   percent = 0
		if(percent>100) percent = 100
		postUpdate(DimmedLight, percent);
end

/**
 * This rule demonstrates how a NumberItem can be used to easily control the local sound system.
 * A selection widget in the UI provides easy access for this
 */
rule "Select Radio Station"
	when
		Item Radio_Station received command
	then
		switch(receivedCommand) {
			case 0 : playStream(null)
			case 1 : playStream("http://metafiles.gl-systemhaus.de/hr/hr3_2.m3u")
			case 2 : playStream("http://mp3-live.swr3.de/swr3_m.m3u")
			case 3 : playStream("http://edge.live.mp3.mdn.newmedia.nacamar.net/radioffh/livestream.mp3.m3u")
		}
end

/**
 * This rules controls the volume on the local host
 */
rule "Volume control"
	when
		Item Volume received command
	then
		if(receivedCommand instanceof PercentType) {
			setMasterVolume(receivedCommand as PercentType)
		} else {
			if(receivedCommand==INCREASE) increaseMasterVolume(20)
			if(receivedCommand==DECREASE) decreaseMasterVolume(20)	
		}
		postUpdate(Volume, masterVolume * 100)
end

rule "Say temperature on update"
	when 
		Item Weather_Temperature received update
	then
		say("The temperature outside is " + Weather_Temperature.state.format("%d") + " degrees celsius")
end

/**
 * The following rules help initializing the demo items with some helpful states.
 */
rule "Initialize light states"
	when
		System started
	then
		Lights?.members.forEach(light|
			postUpdate(light, if(Math::random > 0.7) ON else OFF)
		)
end

rule "Initialize heating states"
	when 
		System started
	then
		Heating?.members.forEach(heating|
			postUpdate(heating, if(Math::random > 0.8) ON else OFF)
		)
end

rule "Initialize contact states"
	when 
		System started
	then
		Windows?.members.forEach(window|
			postUpdate(window, if(Math::random > 0.5) OPEN else CLOSED)
		)
end

rule "Initialize room temperatures"
	when 
		System started
	then
		Temperature?.members.forEach(temperature|
			postUpdate(temperature, 20.0 + (25.0 - (Math::random * 50.0).intValue) / 10.0)
		)
end
