'Returns the parent country for a given record
@param: location: the location or id to search for
@param: key_type: whether to return an id or code
@ToDo: Optimise to not use try/except'

def get_parent_country(self, location, key_type='id'):

    if (not location):
        return None
    db = current.db
    s3db = current.s3db
    try:
        table = s3db.gis_location
        location = db((table.id == location)).select(table.id, table.path, table.level, limitby=(0, 1), cache=s3db.cache).first()
    except:
        pass
    if (location.level == 'L0'):
        if (key_type == 'id'):
            return location.id
        elif (key_type == 'code'):
            ttable = s3db.gis_location_tag
            query = ((ttable.tag == 'ISO2') & (ttable.location_id == location.id))
            tag = db(query).select(ttable.value, limitby=(0, 1)).first()
            try:
                return tag.value
            except:
                return None
    else:
        parents = self.get_parents(location.id, feature=location)
        if parents:
            for row in parents:
                if (row.level == 'L0'):
                    if (key_type == 'id'):
                        return row.id
                    elif (key_type == 'code'):
                        ttable = s3db.gis_location_tag
                        query = ((ttable.tag == 'ISO2') & (ttable.location_id == row.id))
                        tag = db(query).select(ttable.value, limitby=(0, 1)).first()
                        try:
                            return tag.value
                        except:
                            return None
    return None
