from orangescape.model.server.SystemInterface import Data
from orangescape.model.server.sql.SqlUtil import getManyToOneName
import logging
import datetime

class AbstractData(Data, object):

    def __init__(self, SheetId):
        self.SheetId = SheetId

    def setSQLSession(self, sqlSession):
        if sqlSession is None:
            del self.sqlSession
        else:
            self.sqlSession = sqlSession
        return self

    def getSQLSession(self):
        return self.sqlSession

class PrimaryData(AbstractData):

    def get(self, cellMetadata):
        return getattr(self, cellMetadata.getSheetId())

    def set(self, cellMetadata, value):
        if cellMetadata.isReferenceCell():
            oldValue = self.get(cellMetadata)
            if oldValue:
                self.getSQLSession().removeFromCache(self.getSQLSession().getQueryCacheKey(oldValue, cellMetadata))
            if value:
                self.getSQLSession().removeFromCache(self.getSQLSession().getQueryCacheKey(value, cellMetadata))
        setattr(self, cellMetadata.getSheetId(), value)

#    def getReference(self, cellMetadata):
#        if hasattr(self, cellMetadata.getSheetId()+'_cache'):
#            return getattr(self, cellMetadata.getSheetId()+'_cache')
#        parentId = getattr(self, cellMetadata.getSheetId())
#        return parentId
#
#    def setReference(self, cellMetadata, value):
#        referredSheetMetadata = cellMetadata.getReferredSheetMetadata()
#        if value is not None:
#            parentObj = self.getSQLSession().get(value, referredSheetMetadata)
#            setattr(self, getManyToOneName(cellMetadata), parentObj.getDataObject())
#            setattr(self, cellMetadata.getSheetId()+'_cache', parentObj.getDataObject().getSheetId())
#        else:
#            setattr(self, cellMetadata.getSheetId()+'_cache', None)
#            setattr(self, getManyToOneName(cellMetadata), None)

    def setSheetId(self, value):
        setattr(self, self.MetadataName+'_Id', value)

    def getSheetId(self):
        return getattr(self, self.MetadataName+'_Id')

    def getSheetMetadataId(self):
        return self.SheetMetadataId

    def setSheetMetadataId(self, value):
        self.SheetMetadataId = value

    def getCopy(self):
        return self

    def getClass(self):
        return PrimaryData

    SheetId = property(getSheetId, setSheetId)

class OriginalData(AbstractData):
    SheetMetadataId = str()
    SheetId = str()
    ApplicationId = str()
    _dynamic_properties = dict()
    def __init__(self, SheetMetadataId, SheetId, ApplicationId, _dynamic_properties):
        self.SheetMetadataId = SheetMetadataId
        self.SheetId = SheetId
        self.ApplicationId = ApplicationId
        self._dynamic_properties = _dynamic_properties

