'Returns the location hierarchy and it\'s labels
@param: level - a specific level for which to lookup the label
@param: location - the location_id to lookup the location for
currently only the actual location is supported
@ToDo: Do a search of parents to allow this
lookup for any location'

def get_location_hierarchy(self, level=None, location=None):

    _levels = self.hierarchy_levels
    _location = location
    if ((not location) and _levels):
        if level:
            if (level in _levels):
                return _levels[level]
            else:
                return level
        else:
            return _levels
    COUNTRY = current.messages.COUNTRY
    if (level == 'L0'):
        return COUNTRY
    db = current.db
    s3db = current.s3db
    table = s3db.gis_hierarchy
    fields = (table.uuid, table.L1, table.L2, table.L3, table.L4, table.L5)
    query = (table.uuid == 'SITE_DEFAULT')
    if (not location):
        config = GIS.get_config()
        location = config.region_location_id
    if location:
        query = (query | (table.location_id == location))
    rows = db(query).select(cache=s3db.cache, *fields)
    if (len(rows) > 1):
        _filter = (lambda row: (row.uuid == 'SITE_DEFAULT'))
        rows.exclude(_filter)
    elif (not rows):
        if level:
            return level
        levels = OrderedDict()
        hierarchy_level_keys = self.hierarchy_level_keys
        for key in hierarchy_level_keys:
            if (key == 'L0'):
                levels[key] = COUNTRY
            else:
                levels[key] = key
        return levels
    T = current.T
    row = rows.first()
    if level:
        try:
            return T(row[level])
        except:
            return level
    else:
        levels = OrderedDict()
        hierarchy_level_keys = self.hierarchy_level_keys
        for key in hierarchy_level_keys:
            if (key == 'L0'):
                levels[key] = COUNTRY
            elif ((key in row) and row[key]):
                levels[key] = str(T(row[key]))
        if (not _location):
            self.hierarchy_levels = levels
        if level:
            return levels[level]
        else:
            return levels
