import time
from datetime import datetime
startTime = datetime.now()

def convert(duration):
	current_seconds = round(time.time())
	seconds_duration = (current_seconds - (duration/1000))
	m, s = divmod(seconds_duration, 60)
	h, m = divmod(m, 60)
	return seconds_duration
		

def get_timestamp(duration):
	timestamp = system.date.fromMillis(duration)
	return timestamp

def check_device_in_device_list(device, device_list):
    if len(device_list)== 0:
        return True
    for i in device_list:
    	if device.startswith(i):
            return True
    return False

def edit_alarm_id(alarm_id):
	new_alarm_id = alarm_id.replace("/", " / ")
	return new_alarm_id
	
def create_shelve_key(source_id, alarm_id):
	"""
		Creates a formatted key as Ignition ui 
		wont allow "/" and spaces to be stored as 
		key values. Formatting allows easy conversion 
		back to the origional sourceId and message string.
	
		Args:
	    	source_id: The sourceId of the alarm.
	    	message: The alarm message.
	
		Returns:
	    	The formatted key..
	
		Raises:
	    	None.
	"""
	source_to_check = source_id.replace("/", "---")
	key_to_check = source_to_check + "----" + str(alarm_id)
	return key_to_check

def unformat_shelve_key(shelved_key):
	shelved_items = shelved_key.split("----")
	source_to_check = shelved_items[0].replace("---", "/")
	alarm_id = int(shelved_items[1])
	return source_to_check, alarm_id

	
def check_alarm_in_shelved_alarms(source_id, message, alarms_to_shelve):
	key_to_check = create_shelve_key(source_id, message)
	if key_to_check in alarms_to_shelve:
		return key_to_check
	return False

def get_alarm_table(self, active_alarms, severity_filters, no_filter, 
					device_list, alarm_states, alt_colour, table_type):
		alarms_data = []
		alarms_critical = []
		alarms_high = []
		alarms_medium = []
		alarms_low = []
		alarms_diagnostic = []
		alarms_disconnected = []
		alarm_temp_dict = {}
		shelved_alarms_to_keep = {}
		unshelved_alarms_to_keep = {}
		shelve_alarms_dict = self.custom.alarms_to_shelve
		unshelve_alarms_dict = self.custom.alarms_to_unshelve
		if alt_colour:
			style_props_critical = {"classes":"Alarms-Styles/Alt-Colours/Critical"}
			style_props_high = {"classes":"Alarms-Styles/Alt-Colours/High"}
			style_props_medium = {"classes":"Alarms-Styles/Alt-Colours/Medium"}
			style_props_low = {"classes":"Alarms-Styles/Alt-Colours/Low"}
			style_props_diagnostic = {"classes":"Alarms-Styles/Alt-Colours/Diagnostic"}
			style_props_disconnected = {"classes":"Alarms-Styles/NoAlarm-Black"}
			
		else:
			style_props_critical = {"classes":"Alarms-Styles/Critical"}
			style_props_high = {"classes":"Alarms-Styles/High"}
			style_props_medium = {"classes":"Alarms-Styles/Medium"}
			style_props_low = {"classes":"Alarms-Styles/Low"}
			style_props_diagnostic = {"classes":"Alarms-Styles/Diagnostic"}
			style_props_disconnected = {"classes":"Alarms-Styles/NoAlarm-Black"}
		
		for i in active_alarms:
			source_id = active_alarms[i].get("sourceId","Unknown")
			alarm_id =  active_alarms[i].get("id","Unknown")
			severity =  active_alarms[i].get("priority", 0)
			family_type= active_alarms[i].get("type", 0)
			site_id = active_alarms[i].get("siteId", "Unknown")
			state = active_alarms[i].get("state", "Unknown")
			state = alarms.alarm_state.get_alarm_state(state)
			duration = active_alarms[i].get("timestamp", 0)
			time_stamp = get_timestamp(duration)
			active_duration = convert(duration)
			message = active_alarms[i].get("message", "Unknown")
			expiration_epoch = active_alarms[i].get("shelveExpiryEpoch")
			duration_in_minutes = active_alarms[i].get("durationMinutes")
			family_type_Dict={'1':'Jam','2':'Safety /Emergency','3':'Power circuit','4':'Communication',
			'5':'Drive/Motor','6':'Pneumatic','7':'Mechanical','9':'Operational','10':'Scanner',
			'11':'Controller','12':'Unexpected Container','20':'Miscellaneous','0':'Undefined'}
			type_description= family_type_Dict.get(str(family_type))
			
			if expiration_epoch != None:
				expiration = system.date.fromMillis(expiration_epoch * 1000)
			else:
				expiration = "0"	
			
			device_in_list = check_device_in_device_list(source_id, device_list)
			if (int(severity) in severity_filters or no_filter == True) and (
			    device_in_list == True and state in alarm_states):
				if str(active_alarms[i].get("priority")) == "5":
					style_class = style_props_critical
					severity = "5. Critical"
					key = "Critical"
					alarm_list = alarms_critical
	
				elif str(active_alarms[i].get("priority")) == "4":
					style_class = style_props_high
					severity = "4. High"
					key = "High"
					alarm_list = alarms_high
				
				elif str(active_alarms[i].get("priority")) == "3":
					style_class = style_props_medium
					severity = "3. Medium"
					key = "Medium"
					alarm_list = alarms_medium
				
				elif str(active_alarms[i].get("priority")) == "2":
					style_class = style_props_low
					severity = "2. Low"
					key = "Low"
					alarm_list = alarms_low
				
				elif str(active_alarms[i].get("priority")) == "1":
					style_class = style_props_diagnostic
					severity = "1. Diagnostic"
					key = "Diagnostic"
					alarm_list = alarms_diagnostic
				
				elif str(active_alarms[i].get("priority")) == "6":
					style_class = style_props_disconnected
					severity = "Disconnected"
					key = "Disconnected"
					alarm_list = alarms_disconnected
				
				else: 
					style_class = style_props_diagnostic
					severity = "Unknown"
					key = "Diagnostic"
					alarm_list = alarms_diagnostic
				
				if table_type == "Docked-East":
					source_id = edit_alarm_id(source_id)
				
				shelve_alarm_id = check_alarm_in_shelved_alarms(source_id, alarm_id, shelve_alarms_dict)
				if shelve_alarm_id:
					shelved_alarms_to_keep[shelve_alarm_id] = ""
					shelve_alarm = True
				else:
					shelve_alarm = False
				
				unshelve_alarm_id = check_alarm_in_shelved_alarms(source_id, alarm_id, unshelve_alarms_dict)
				if unshelve_alarm_id:
					unshelved_alarms_to_keep[unshelve_alarm_id] = ""
					unshelve_alarm = True
				else:
					unshelve_alarm = False
					
				row = row_builder.build_row( SourceId = source_id, Priority = severity, Type = type_description,
				Timestamp = time_stamp, State = state,
				Message = message, Expiration = expiration,
				Duration = active_duration, Alarm_id = alarm_id, Shelve = shelve_alarm,
				Unshelve = unshelve_alarm, StyleClass = style_class)
				alarm_list.append(row)
		
		
		for k,v in shelve_alarms_dict.items():
			if k not in shelved_alarms_to_keep:
				self.custom.alarms_to_shelve.pop(k)
		
		for k,v in unshelve_alarms_dict.items():
			if k not in unshelved_alarms_to_keep:
				self.custom.alarms_to_unshelve.pop(k)
		
		return alarms_critical + alarms_high + alarms_medium + alarms_low + alarms_diagnostic +  alarms_disconnected
