import logging
import datetime
from orangescape.model.engine.exception.Error import MetadataError
from orangescape.model.server.integration.AbstractIntegrationService import AbstractIntegrationService
from orangescape.model.server.util.ConversionUtil import format_record

class WebServicesIntegrationService(AbstractIntegrationService):
    session = None
    userid=None
    metadata=None
    def __init__(self,metadata,session):
        self.update = True
        self.session=session
        self.initializeSession("guest")
        self.metadata=metadata

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

    def process(self, metadata,iterableData):
        self.metadata=metadata
        params={}
        childInstances={}
        for key in iterableData:
            paramDict=iterableData[key]
            for param in paramDict:
                if type(paramDict[param]) is not dict:
                    params[param]=paramDict[param]
                else:
                    for childParams in paramDict[param]:
                        childInstances[childParams]= paramDict[param][childParams]
        record = format_record(self.component, metadata, params)
        if self.update:
            sheet = self.__update__(record)
        else:
            sheet = self.__insert__(record)
        for childItem in childInstances:
            refCell= childItem.split('.')[0]
            childSheet= childItem.split('.')[1]
            childParams=childInstances[childItem]
            childParams[refCell]=sheet.getSheetId()
            parentSheetMetadata=self.session.getApplication().getSheetMetadata(childSheet)
            self.process(parentSheetMetadata,{childSheet:childParams})
        self.session.commit()
        return sheet

    def __insert__(self, record):
        return 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:
            return self.__insert__(record)
        else:
            return self.component.update(dbRecord, record)
