# Definition of tag location to store tagpaths and updated data. 
tagpath = '[default]System/DataTables/DOAS'
udt_type = 'Objects/Air/DOAS'
sub_paths = {
	'OAD':'/Outdoor Air Dewpoint',
	'BP':'/Building Pressure',
	'SAT':'/Supply Air Temperature',
	'SAD':'/Supply Air Dewpoint'
}
	
def update_data(config_tagpath, sub_paths_map):
	'''
	config_tag_path: Path to the memory tag that contains the JSON with all the paths
	sub_paths_map: Dictionary that maps all the sub_paths with the tag to be used in the table.
	'''
	# 1. Read the list of tagpaths.
	raw_data = system.tag.readBlocking(config_tagpath + '/Data')[0].value
	paths_list = raw_data.get('paths', [])
	if not paths_list:
		return []
	# Order the keys to make sure the reading loop is consistent
	col_names = sub_paths_map.keys()
	
	# 2. Build the reading list
	read_paths = []
	for path in paths_list:
		for col in col_names:
			read_paths.append(path + sub_paths_map[col])
	# 3. Read all the values in one execution
	reads = system.tag.readBlocking(read_paths)
	
	# 4. Process the result
	output = []
	num_cols = len(col_names)
	for device_idx, path in enumerate(paths_list):
		item = {"device": path.split('/')[-1]}
		for col_idx, col in enumerate(col_names):
			global_idx = (device_idx * num_cols) + col_idx
			tag_value = reads[global_idx].value
			
			
			item[col] = tag_value if tag_value is not None else "0"
		output.append(item)
	return output
		
def update_tagpaths():
	raw_paths = equipment.common.get_tagpaths(udt_type)
	paths = [str(p) for p in raw_paths]
	document = {'paths':paths}
	system.tag.writeBlocking(tagpath + '/Data', document)