########################################################################
#
# File Name: 	       Relationship.py
#
# Documentation:	http://docs.ftsuite.com/4ODS/Relationship.py.html
#
"""
Implements the Relationship meta-data interface.
WWW: http://4suite.org/4ODS         e-mail: support@4suite.org

Copyright (c) 1999 Fourthought, Inc., USA.   All Rights Reserved.
See  http://4suite.org/COPYRIGHT  for license and copyright information
"""

from Ft.Ods.MetaData import MetaKind
from Ft.Ods.MetaData import Cardinality
from Ft.Ods.MetaData import Property

from Ft.Ods.StorageManager.Adapters import Constants
from Ft.Ods import PersistentObject
td = PersistentObject.TupleDefinitions

class Relationship(Property.Property):
    def __init__(self,db,data):
        Property.Property.__init__(self, db, data,MetaKind.mk_relationship)
        

    def get_cardinality(self):
        ourCard = self._4ods_getCardinality()
        thierCard = self.__dict__['traversal']._4ods_getCardinality()
        return g_cardinalityMap[ourCard][thierCard]

    def form_traversal(self,trav,inverse = 1):
        self._4ods_formRelationship('traversal',Relationship,'traversal','form',trav,inverse)

    def drop_traversal(self,trav,inverse=1):
        self._4ods_dropRelationship('traversal','traversal','drop',trav,inverse)
    
    def _4ods_getOdl(self,indent):
        inv = self.traversal.absolute_name()
        if self.type.meta_kind == MetaKind.mk_collection:
            st = indent+'relationship %s %s inverse %s' % (self.type._4ods_getOdl(''),self.name,inv)
        else:
            st = indent+'relationship %s %s inverse %s' % (self.type.absolute_name(),self.name,inv)
        return st

    def _4ods_getCardinality(self):
        from Ft.Ods.MetaData import Collection
        if isinstance(self.type,Collection.Collection):
            return 'N'
        return '1'

    def _4ods_checkRemove(self):
        return 1

    def _4ods_getGeneratedMetaClasses(self,found,checked):
        if self in checked: return
        checked.append(self)
        self.type._4ods_getGeneratedMetaClasses(found,checked)


    _tupleNames = (('traversal',),)

    _tupleDefinitions = {'traversal':{td.TYPE:Constants.Types.ROBJECT,
                                      td.READONLY:1,
                                      td.RELATIONSHIP:1,
                                      },
                         }
    _localExtents = ()

g_cardinalityMap = {'1': {'1':Cardinality.Cardinality.c1_1,
                          'N':Cardinality.Cardinality.c1_N
                          },
                    'N': {'1':Cardinality.Cardinality.cN_1,
                          'N':Cardinality.Cardinality.cN_N
                          }
                    }
