import csv
from StringIO import StringIO

def check_csv_file(event):
	"""
		This function checks if the CSV file was saved as CSV-UF8 settings if it has removes extra data bytes from the file.
	
		Args:
	    	event : Containes the file data to be uploaded

		Returns:
	    	a string representing the file that is to be uploaded.
	
		Raises:
	    	None
	"""
	file_bytes = event.file.getBytes()
	if bytearray.fromhex("ef bb bf") == bytearray(file_bytes[0:3]):
		# Strip first three bytes
		file_bytes = file_bytes[3:]
	return file_bytes.tostring()
	
	
def add_device_btn_code(whid, event):

	reader = csv.DictReader(StringIO(FileHandler.uploader.check_csv_file(event)))
	data ={}
	def get_child():
		return {
			"Area":"",
			"SubArea":""
		}

	for i, v in enumerate(reader):
		child = get_child()
		child["Area"] = v["Area"]
		child["SubArea"] = v["SubArea"]
		data[v["Device"]]= child


	system.tag.writeBlocking(["[%s_SCADA_TAG_PROVIDER]Configuration/PLC"%whid], system.util.jsonEncode(data))
	
	return "Success"
	
def add_detailed_view_btn_code(whid, event):

	reader = csv.DictReader(StringIO(FileHandler.uploader.check_csv_file(event)))

	data ={}

	def convert_dict_value_to_list(string):
		device_list = []
		for i in string.replace("#", ",").split(","):
			device_list.append(i.strip())
		return device_list

	for v in reader:

		data[v["DetailedView"]]= convert_dict_value_to_list(v["Devices"])


	system.tag.writeBlocking(["[%s_SCADA_TAG_PROVIDER]Configuration/DetailedViews"%whid], system.util.jsonEncode(data))
	
	return "Success"