# List of enabled gateways, 
gtwys = ['[default]']

def get_tagpaths(udt_type):
	fltr = {"typeId":udt_type, "tagType":"UdtInstance", "recursive":True}
	paths_list = []
	for location in equipment.common.gtwys:
		results = system.tag.browse(location, fltr)
		for result in results:
			paths_list.append(str(result['fullPath']))
	return paths_list
	
def update_data(destination_tag, paths_list, 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.
	'''
	logger = system.util.getLogger("DataTableUpdates")
	try:
		col_names = sub_paths_map.keys()
		
		# 1. Build the reading list
		read_paths = []
		for path in paths_list:
			for col in col_names:
				read_paths.append(path + sub_paths_map[col])
		# 2. Read all the values in one execution
		reads = system.tag.readBlocking(read_paths)
		
		# 3. Process the result
		data = []
		num_cols = len(col_names)
		for device_idx, path in enumerate(paths_list):
			item = {'device': path.split('/')[-1], 'path': path}
			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"
			data.append(item)
		
		document = {'data':data}
		system.tag.writeBlocking([destination_tag], document)
	except Exception as e:
		logger.error("Fail to update data (%s): %s" % (destination_tag, str(e)))

def style_table(data_dic):
	output = []
	for element in data_dic:
		try:
			severity = int(element.get('Alm', 0 ))
		except (TypeError, ValueError):
			severity = 0
		item = {
			"value": element,
			"style": {}
		}
		if severity > 0:
			item['style'] = alarm.summary.get_severity_style(severity)
		output.append(item)
	return output