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.getGeneratorBase(), location)
	return baseTagPaths

def getHistoryLastValues(genBasePath, pqmBasePath, sDate, eDate):
	tagpaths = ["%s/Fuel Percent"%(genBasePath), "%s/Fuel Gallons"%(genBasePath), "%s/Real Power"%(pqmBasePath)]
	pyDS = reports.MBR.common.util.getHistory(tagpaths, sDate, eDate, customArgs={"noInterpolation":False})
#	print tagpaths, len(pyDS)
	return  [c for c in pyDS[-1]]

def buildFinalTable(startDate,endDate,location=None):
	lastValueStartDate = system.date.addMinutes(endDate, -10)
	header = ["Generator", "FuelPercent","FuelGal","RatedLoading","CurrentLoading","RunHours"]
	allRows = []
	for genPath,pqmPath in getTagPaths(location):
		genName = genPath.split("_")[-1].replace("GEN-","")
		tstamp, fuel_perc, fuel_gal, curLoad = getHistoryLastValues(genPath, pqmPath, lastValueStartDate, endDate)
		# now get the meta values
		fullLoadKW, fullLoadGPH= [t.value for t in system.tag.readBlocking(["%s/Meta/Full Load kW"%genPath,"%s/Meta/Full Load GPH"%genPath])]
		if fullLoadGPH is None:
			fullLoadGPH = 180.0
		if fuel_gal is None:
			fuel_gal = 1500
		allRows.append([genName,fuel_perc,fuel_gal,fullLoadKW,curLoad, fuel_gal/fullLoadGPH])

	return system.dataset.sort(system.dataset.toDataSet(header, allRows), "Generator", True)