from orangescape.model.engine.Component import Component
from orangescape.model.server.util.ConversionUtil import format_record

class AbstractIntegrationService:

    def initializeSession(self,userid):
        self.application = self.session.getApplication()
        self.component = Component(self.session)
        userins = self.session.get(userid, self.getSheetMetadata('User'))
        self.session.setUser(userins)

    def setSession(self,session):
        self.session=session
        self.component = Component(self.session)

    def setUserId(self,userId):
        self.userid=userId

    def getSheetMetadata(self,sheetMetadataName):
        return self.session.getApplication().getSheetMetadata(sheetMetadataName)

    def __process__(self, iterableData):
        for csvData in iterableData:
            record = format_record(self.component, self.metadata, csvData)
            if self.update:
                self.__update__(record)
            else:
                self.__insert__(record)
        self.session.commit()

    def __insert__(self, record):
        self.component.new(self.metadata, record)

    def __update__(self, record):
        dbRecord = None
        sheetId = record.get('SheetId')
        if sheetId is not None:
            dbRecord = self.session.getIfExists(sheetId, self.metadata)
        else:
            sheetName = record.get('SheetName')
            if sheetName is not None:
                dbRecord = self.session.getBySheetName(sheetName, self.metadata)

        if dbRecord is None:
            self.__insert__(record)
        else:
            self.component.update(dbRecord, record)
