from datetime import datetime

def getTagPaths(location=None):
	"""
		Get all the relvant tagpaths needed for the historian query
	"""
	baseTagPaths = reports.MBR.common.util.getBaseTagPaths(reports.MBR.common.static.getUtilitySES(), location)
	return baseTagPaths

def getEnergyHistory(startDate, endDate, location=None):
	tagpaths = ["%s/Real Energy"%(path) for path in getTagPaths(location)]
	return reports.MBR.common.util.getHistory(tagpaths, startDate, endDate, customArgs={})

def getRealPowerHistory(startDate,endDate, location=None):
	tagpaths = ["%s/Real Power"%(path) for path in getTagPaths(location)]
	return reports.MBR.common.util.getHistory(tagpaths, startDate, endDate, customArgs={"intervalMinutes":60})
	

def generateEnergyData(startDate, endDate, location=None):
	"""
		We'll take the actual start and end dates, but because we only care about the first entry and last entry we'll do
		2 queries to get the head and tail of the range
	"""
	qStart = startDate
	qEnd = system.date.addMinutes(startDate, 10)
	hist = getEnergyHistory(qStart, qEnd, location)
	energyStart, energyEnd = (), ()
	if len(hist)>0:
		energyStart= (hist[0][1], hist[0][2])

	qStart = system.date.addMinutes(endDate, -10)
	qEnd = endDate
	hist = getEnergyHistory(qStart, qEnd, location)
	if len(hist)>0:
		energyEnd= (hist[-1][1], hist[-1][2])	
	return energyStart, energyEnd
	
def generateRealPowerTrend(startDate,endDate, location=None):
	hist = getRealPowerHistory(startDate, endDate, location)
	return reports.MBR.common.util.generateSumCol(hist, "SumRealPwr")
	
def getRawData(startDate,endDate, intervalMins = 15, location=None):
	# Try doing this the direct way through historian
	tagpaths = ["%s/Real Power"%(path) for path in getTagPaths(location)] + ["%s/Real Energy"%(path) for path in getTagPaths(location)]
	return system.dataset.toPyDataSet(
		system.tag.queryTagHistory(tagpaths, startDate, endDate, intervalMinutes= intervalMins, 
								columnNames= ["SES-1A Pwr","SES-1B Pwr", "SES-1A Energy", "SES-1B Energy"], 
								aggregationModes=["SimpleAverage","SimpleAverage","LastValue","LastValue"], noInterpolation=True, 
								ignoreBadQuality=True)
		)

def doReport(startDate, endDate, intervalMin= 15):
	"""
		This report runs only for the SES1A and SES1B yard.
	"""
	res= {"RealPower":None, "RealEnergy":{}}
	sEnergy, eEnergy= generateEnergyData(startDate,endDate, "Yard")
	res["RealEnergy"]["1A"] = {"Start":sEnergy[0], "End":eEnergy[0]}
	res["RealEnergy"]["1B"] = {"Start":sEnergy[1], "End":eEnergy[1]}
	
	powerChart = generateRealPowerTrend(startDate, endDate, "Yard")
	oldHeader = system.dataset.getColumnHeaders(powerChart)
	newHeader = ["t_stamp", "SES_1A", "SES_1B", "SumPower"]
	allRows = [[row[c] for c in oldHeader] for row in powerChart]
	
	res["RealPower"] = system.dataset.toDataSet(newHeader, allRows)
	res["RawData"] = reports.MBR.utility.getRawData(startDate,endDate, intervalMin, "Yard")
	return res
	
