import re
import os
import json
import sys
#Stores the page configuration for the project. 
#This global variable is accesible form all gateway scoped events using "." notation
#congig.project_config.global_project_page_ids
global_project_page_ids = {}



def get_project_config():
    """
    	Function searches through the project directory Detailed-Views. 
    	It looks for all the source ids on each Detailed-View and returns a
    	Dict with source ids as the keys and page ids as the values.
    
    	Args:
        	param1: self. refrence to the object being called.
        	param2: source_id. The source_id of the alarm.
    
    	Returns:
        	N/A.
    
    	Raises:
        	KeyError: Will log an error message to the console if the basepath is not found.
        	          logger = {whid}_get_project_config
    """
    if not global_project_page_ids:
	    try:
	        basePath = os.getcwd().replace('\\','/') + '/data/projects/' + system.util.getProjectName() + '/com.inductiveautomation.perspective/views/Detailed-Views'
	        files = os.listdir(basePath)
	        files_found = True
	    except:
	        whid = system.tag.readBlocking("Configuration/FC")[0].value
	        logger = system.util.getLogger("%s-get_project_config" % (whid))
	        exc_type, exc_obj, tb = sys.exc_info()
	        lineno = tb.tb_lineno
#	        logger.error("Error: %s, %s, %s" % (lineno, exc_type, exc_obj)) #JCM
	        files_found = False
	    if files_found:
	        for i in files:
	            jsonPath = basePath+'/'+str(i)+'/view.json'
	            with open(jsonPath, 'r') as f:
	                data= f.read()
	            obj = json.loads(data)
	            for child in obj['root']['children']:
	                tag_props = child.get("props",{}).get("params", {}).get("tagProps")
	                if tag_props:
	                    source_id = tag_props[0]
	                    global global_project_page_ids
	                    global_project_page_ids[source_id] = i

def open_pop_up(message):
	error_message = message 
	system.perspective.openPopup("ErrorPopUP", "PopUp-Views/Error", 
								params ={"Error_message":error_message}, 
								showCloseIcon = False, modal = True,
								viewportBound = True,
								draggable = False,
								overlayDismiss = True
								)




def navigate_to_url(self, source_id, page_id):
    url_to_navigate = "/DetailedView/%s/%s" % (page_id, page_id)
    navigation.amzl_navigation.set_session_variables(self, source_id, False)
    system.perspective.navigate(page = url_to_navigate)
       
def source_id_lookup(self, source_id):
    """
    	This function looks for the source_id in 
    	the global_project_page_ids variable. 
    	If found it returns the corrresponding page id. 
    	If no page id is found it will search up the hierachy 
    	of the source_id until it finds a match. It will then 
    	navigate the user to the correct page and set the session 
    	custom variable search_id.
    
    	Args:
        	param1: self. refrence to the object being called.
        	param2: source_id. The source_id of the alarm.
    
    	Returns:
        	N/A.
    
    	Raises:
        	KeyError: N/A.
    """
    logger = system.util.getLogger("Naviagtion function") 
#    logger.info(str(global_project_page_ids))
    page_id = global_project_page_ids.get(source_id)
    found = False
    if page_id:
        found = True
        navigate_to_url(self, source_id, page_id)
    else:
        items = source_id.split("/")
        length_of_items = len(items)-1
        while length_of_items > 0:
            items.pop()
            source_id = "/".join(items)
            page_id = global_project_page_ids.get(source_id)
            if page_id:
                found = True
                navigate_to_url(self, source_id, page_id)
                break
            length_of_items -= 1       	        
    	if not found:
    	    open_pop_up("No page id found")

def get_child_scada_projects():
	"""
		This function returns an alphabetically sorted list of 
	child SCADA projects, that inherit the SCADA_PERSPECTIVE_PARENT_PROJECT.
	Each of these projects follow the naming convention "{WHID}_SCADA"
	
	:return: List[str]; List of project names on gateway
	"""   	
	pattern = '[A-Z]{3}[0-9]|K[A-Z]{3}_SCADA'
	all_projects = system.project.getProjectNames()
	return sorted([x for x in all_projects if re.match(pattern, x)])
