import logging
subParentRefCellId = {
           'CellMetadata_a4968f28_8059_46d7_89fc_23447955440d': 'SheetMetadata-ShortCut',
           'CellMetadata_25a74a89_a7d2_4c99_924a_1e722a54b44d': 'ActivityDefinition-ActivityPermission',
           'CellMetadata_92d949d3_b866_4d89_96a2_5c99bdae6fff': 'CellMetadata-InputportMetadata',
           'CellMetadata_f4f210e5_dbd1_4451_9b0d_47fa1390b60c': 'CellMetadata-OutputportMetadata',
           }

def getBelongingSheetId(session, instance):

    if instance.getSheetMetadata().getSheetId()=='Sheet001':
        return instance.getSheetId()

    if instance.getSheetMetadata().getPublicCellMetadataDict().has_key('BelongingSheetId'):
        if instance.getValue('BelongingSheetId'):
            return instance.getValue('BelongingSheetId')
        logging.warn('Please Do BelongingSheetId migration for %s %s'%(instance.getSheetMetadata().getSheetName(), instance.getSheetId()))
    else:
        logging.warn('System parameter BelongingSheetId cell not found in the metadata %s'%(instance.getSheetMetadata().getSheetName()))

    """For GridView should navigate through GridCell if it contains GridCell"""
    if instance.getSheetMetadata().getSheetId()=='Sheet011':
        foreignKeyValue = instance.getValue('GridCell')
        if foreignKeyValue:
            parent = session.get(foreignKeyValue, instance.getCellMetadata('GridCell').getReferredSheetMetadata())
            return getBelongingSheetId(session, parent)
        foreignKeyValue = instance.getValue('SheetMetadata')
        if foreignKeyValue:
            parent = session.get(foreignKeyValue, instance.getCellMetadata('SheetMetadata').getReferredSheetMetadata())
            return getBelongingSheetId(session, parent)
    logging.info('Trying to get System patameter belongingSheetId through relation for %s %s'%(instance.getSheetMetadata().getSheetName(), instance.getSheetId()))
    for refCell in instance.getSheetMetadata().getManyToOneList():
        if refCell.isCascade() and not subParentRefCellId.has_key(refCell.getSheetId()):
            foreignKeyValue = instance.get(refCell)
            if foreignKeyValue:
                parent = session.get(foreignKeyValue, refCell.getReferredSheetMetadata())
                return getBelongingSheetId(session, parent)

