"""
This class implements the base infrastructure to handle themes, the class must leverage
default themes will be stored in layout.root._assets.themes, The expected files in a theme are the following:
    - borders
    - buttons
    - layout
    - menu
    - header
If the following are not available then we should load the default one. 
This would avoid crashes but would come at the expense of a lack of consistent visual layout (alas)
"""
import git
import requests
import os
URL = os.environ['QCMS_HOST_URL'] if 'QCMS_HOST_URL' in os.environ else 'https://dev.the-phi.com/git/qcms/themes.git'
def current (_system) :
    return _system['theme']
def List (_url = URL) :
    """
    calling qcms to list the available URL
    """
    try:
        # _url = '/'.join([_url,'api','themes','List'])
        # return requests.get(_url).json()

        remote_refs  = git.cmd.Git().ls_remote(_url, heads=True)
        
        return [ref.split("\t")[1].replace("refs/heads/", "") for ref in remote_refs.splitlines()]

    except Exception as e:
        
        pass
    return []
def Get(theme,path,_url= URL) :
    """
    This function retrieves a particular theme from a remote source
    The name should be in the list provided by the above function
    """
    try:
        # _url = '/'.join([_url,'api','themes','Get']) +f'?theme={theme}'
        try:
            # return requests.get(_url).json()
            path  = path if '_assets/themes' in path else os.sep.join([path,'_assets','themes'])
            if not os.path.exists(path) :
                os.makedirs(path)
            
            if not os.path.exists ( os.sep.join([path,theme]) ) :
                _loc = os.sep.join([path,theme])
                repo = git.Repo.clone_from(_url, _loc,branch=theme,depth=1)
        except Exception as e:
            print(e)
            pass
        return None
    except Exception as e:
        pass
    return {}
def Installed (path):
    return os.listdir(os.sep.join([path,'_assets','themes']))
def UpdateTheme(path,name,url) :
    """
    :path   root folder of the qcms app/site
    :name   name of the theme bing updated
    :url    url of the git repository
    """
    _themerepo = os.sep.join([path,'_assets','themes',name])
    repo = git.Repo(_themerepo)
    repo.remotes.origin.pull()
def Set(theme,_system) :
    _system['theme'] = theme
    return _system
