# required imports to create the OpValue return object.
from hec.rss.model import OpValue
from hec.rss.model import OpRule

# addtional imports for this script
from hec.hecmath import *
from hec.heclib.dss import *
import bisect


# runRuleScript() is the entry point that is called during the
# compute.
#
# currentRule is the rule that holds this script
# network is the ResSim network
# currentRuntimestep is the current Run Time Step
def runRuleScript(currentRule, network, currentRuntimestep):

	# create new Operation Value (OpValue) to return
	opValue = OpValue()

	tscP25 = currentRule.varGet("tscP25")
	tscP50 = currentRule.varGet("tscP50")
	inflowTS = network.getTimeSeries("Reservoir","Folsom", "Pool", "Flow-IN")

	if tscP25 == None or tscP50 == None:
		pathname = network.makeAbsolutePathFromWatershed("shared\dss\Folsom_EventTimeSeries.dss")
		dssFile = HecDss.open(pathname)
		dssFile.setTimeWindow("31Dec1899 2400", "31Dec1900 2400")
		tscP25 = dssFile.get("/AMERICAN/FOLSOM/FLOW-RES IN-P25//1HOUR/[24FEB1955-31MAR2009] OLYPMIC SMOOTHING (25 HOURS)/")
		tscP50 = dssFile.get("/AMERICAN/FOLSOM/FLOW-RES IN-P50//1HOUR/[24FEB1955-31MAR2009] OLYPMIC SMOOTHING (25 HOURS)/")
		currentRule.varPut("tscP25",tscP25)
		currentRule.varPut("tscP50",tscP50)
		
	
	hTime = currentRuntimestep.getHecTime()
	hTimeValue = hTime.value() * 60
	i = bisect.bisect_left(tscP25.times, hTimeValue)
	
	P25 = tscP25.values[i]
	P50 = tscP50.values[i]
	inflow = inflowTS.getCurrentValue(currentRuntimestep)
	
	message = currentRuntimestep.dateTimeString() + "   Time Granularity = %s " % hTime.getTimeGranularity()
	network.printLogMessage(message)
	message = currentRuntimestep.dateTimeString() + "   hTimeValue = %s " % hTimeValue
	network.printLogMessage(message)
	message = currentRuntimestep.dateTimeString() + "  tscP25.times[%d]  = %s " % (i, tscP25.times[i])
	network.printLogMessage(message)
	message = currentRuntimestep.dateTimeString() + "  tscP25.values[%d]  = %s " % (i, tscP25.values[i])
	network.printLogMessage(message)
	
	network.printLogMessage("\n")
	
	if inflow < P25:
		minRel = inflow
	elif  inflow < P50:
		minRel = 1100
	else:
		minRel = 2400
	

	# set type and value for OpValue
	#  type is one of:
	#  OpRule.RULETYPE_MAX  - maximum flow
	#  OpRule.RULETYPE_MIN  - minimum flow
	#  OpRule.RULETYPE_SPEC - specified flow
	opValue.init(OpRule.RULETYPE_MIN, minRel)

	# return the Operation Value.
	# return "None" to have no effect on the compute
	return opValue