import os

from . import const

USERAPPS_DIR = os.getenv('USERAPPS_DIR', '/opt/rtcds/userapps/release').rstrip('/')

SUBSYSTEMS = [
    'als',
    'asc',
    'cal',
    'hpi',
    'ioo',
    'isc',
    'isi',
    'lsc',
    'omc',
    'psl',
    'sus',
    'sqz',
    'sys',
    'tcs',
    ]

if const.SITE and const.IFO:
    DEFAULT_ARCHIVE_ROOT = os.path.join('/ligo', 'cds',
                                        const.SITE.lower(),
                                        const.IFO.lower(),
                                        'guardian', 'archive')
else:
    DEFAULT_ARCHIVE_ROOT = None
ARCHIVE_ROOT = os.getenv('GUARD_ARCHIVE_ROOT', DEFAULT_ARCHIVE_ROOT)


class LigoPathError(Exception):
    pass

def userapps_path(*args):
    """Return full path in LIGO userapps for given specified subdirectories.

    Works like os.path.join.

    """
    return os.path.abspath(os.path.join(USERAPPS_DIR, *args))

def userapps_subpath_from_path(path):
    """For path in LIGO userapps, return subpath relative to userapps root.

    """
    path = os.path.expanduser(path).rstrip('/')
    uap = USERAPPS_DIR + '/'
    if os.path.commonprefix([path, uap]) != uap:
        raise LigoPathError('specified path is not in USERAPPS.')
    return os.path.relpath(path, USERAPPS_DIR)

def userapps_subsys_from_path(path):
    """For path in LIGO userapps, return subsystem to which it belongs.

    """
    subpath = userapps_subpath_from_path(path)
    if subpath:
        return subpath.split('/')[0]

def userapps_guardian_paths(subsyss=SUBSYSTEMS, ifo=None):
    """Return list of Guardian site-specific and common paths for list of subsystems.

    Site-specific paths will be ordered before the corresponding common path.

    If subsystem not specified, path list for all subsystems will be returned.

    If ifo is not specified, IFO environment variable will be used.

    """
    if not ifo:
        ifo = const.IFO
    if ifo:
        ifo = ifo.lower()
    paths = []
    for subsys in subsyss:
        if ifo:
            paths += [os.path.join(USERAPPS_DIR, subsys, ifo, 'guardian')]
        paths += [os.path.join(USERAPPS_DIR, subsys, 'common', 'guardian')]
    return paths
