from datetime import datetime
def getBaseTagPaths(locations=[]):
	"""
		Get a list of tagpaths from SES1A/SES1B or the selected datahalls.	
	"""
	baseTagPaths = []
	if len(locations) > 0:
		for location in locations:
			baseTagPaths+= reports.MBR.common.util.getBaseTagPaths(reports.MBR.common.static.getPQMBase(), location)
	else:
		baseTagPaths = reports.MBR.common.util.getBaseTagPaths(reports.MBR.common.static.getUtilitySES(), "Yard")
	return baseTagPaths
	

def getEnergyPaths(locations):
	return ["%s/Real Energy"%(path) for path in getBaseTagPaths(locations)]

def getRawData(startDate, endDate, locations):
	"""
		Get per minute data for all of the energy paths.
	"""
	energyTagPathsSES = getEnergyPaths([])
	energyTagPathsAreas = getEnergyPaths(locations)
	sesHist = reports.MBR.common.util.getHistory(energyTagPathsSES, startDate, endDate, customArgs={})
	areaHist = reports.MBR.common.util.getHistory(energyTagPathsAreas, startDate, endDate, customArgs={})
	
	return sesHist, areaHist 
	
def calculateDelta(dataset, sumColName):
	"""
		Pass in the dataset and use the sumColName to indicate which column the delta will be performed
		Args:
			dataset: PyDataset of rawhist and sum column
			sumColname: name of the column the sum resides in
		Returns:
			List of calculated deltas
	"""
	deltaList = []
	for i,row in enumerate(dataset):
		if i == 0:
			deltaList.append(0)
		else:
			deltaList.append(row[sumColName]-dataset[i-1][sumColName])
	return deltaList

def processRawData(startDate, endDate, locations, intervalMins=15):
	"""
		Retrieve the raw history minute data, then create the new columns	
	"""
	# PyDS
	sesDS, areaDS = getRawData(startDate, endDate, locations)
	sesDS = reports.MBR.common.util.generateSumCol(reports.MBR.common.util.averageIntervalData(sesDS, intervalMins), sumColName="SESTotalEnergy")
	areaDS = reports.MBR.common.util.generateSumCol(reports.MBR.common.util.averageIntervalData(areaDS, intervalMins), sumColName="ExclAreaTotalEnergy")
	
	sesDeltaList = calculateDelta(sesDS, "SESTotalEnergy")
	areaDeltaList = calculateDelta(areaDS, "ExclAreaTotalEnergy")
	finalDS = sesDS

	if len(sesDeltaList) == len(areaDeltaList):
		deltaDiffList  = [a-b for a,b in zip(sesDeltaList, areaDeltaList)]
	
		# merge the 2 SES and Area Datasets
#		try:
		finalDS = reports.MBR.common.util.mergeHistorianData(sesDS, areaDS)
		finalDS = system.dataset.addColumn(finalDS, sesDeltaList, "SES Consumed", float)
		finalDS = system.dataset.addColumn(finalDS, areaDeltaList, "Excluded Area Consumed", float)
		finalDS = system.dataset.addColumn(finalDS, deltaDiffList, "Tenant Consumed", float)
			
#		except:
#			pass
	else:
		finalDS = system.dataset.addColumn(finalDS, col= sesDeltaList, colName="SES Consumed", colType=float)
	
	return finalDS
	