# 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(result['fullPath'])
	return paths_list

def update_tagpaths(data_tagpath, udt_type):
	raw_paths = get_tagpaths(udt_type)
	paths = [str(p) for p in raw_paths]
	document = {'paths':paths}
	system.tag.writeBlocking(data_tagpath + '/Paths', document)
	
def update_data(data_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.
	'''
	logger = system.util.getLogger("DataTableUpdates")
	try:
		# 1. Read the list of tagpaths.
		read_config = system.tag.readBlocking(data_tagpath + '/Paths')
		raw_data = read_config[0].value
		if not raw_data or 'paths' not in raw_data:
			logger.warn("Empty configuration: %s" % data_tagpath)
			return
		# Order the keys to make sure the reading loop is consistent
		paths_list = raw_data.get('paths', [])
		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
		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(data_tagpath + '/Data', document)
	except Exception as e:
		logger.error("Fail to update data (%s): %s" % (data_tagpath, 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