import logging
from orangescape.model.engine.execution.ProcessUtil import getProcessCell_PrefixName
from orangescape.model.engine.engineconstants import PI_CELLNAME
import appconfig as config
import urllib

def authenticateIntegration(session, authString, controller=None):
    import base64
    username, password = base64.decodestring(authString.replace('Basic ','')).split(':', 1)
    applicationObj = session.getApplication()
    userins=session.getBySheetName(username,applicationObj.getSheetMetadata('User'))
    if not userins:
        return {"error":"User not found for id "+username}
    if userins.getValue('UserProfile')!='Integration':
        return {"error":"Authentication failed. This user is not assigned integration privileges."}
    userId=userins.getValue('UserId')
    passwd=userins.getValue('Password')
    if password!=passwd or userId!=username:
        return {"error":"Authentication failed. The username or password is wrong."}
    session.setUser(userins)
    if controller:
        from orangescape.auth.Dummy import checkCookies
        checkCookies(controller, username)
    return {"success":userins}

def dispatchCommand(session, command, *args):
    from orangescape.model.engine.Component import Component
    component = Component(session)
    command_method = getattr(component,command)
    return command_method(*args)

def getUrlParams(url):
    url=urllib.unquote(url)
    path=url[1:len(url)].split('/')
    return path

def __get_process_instance_Id__(session, activitydefId, metadataId, sheetId):
    applicationObj = session.getApplication()
    metadata = applicationObj.getSheetMetadataById(metadataId)
    activityDefinition = metadata.getActivityDefinitionById(activitydefId)

    prefix_name = getProcessCell_PrefixName(activityDefinition)

    sheet = session.get(sheetId, metadata)
    piId = sheet.getValue(prefix_name+PI_CELLNAME)
    return piId

def getResponseXSD(session, formName, rootSheetMetadata):
        applicationObj = session.getApplication()
        children = applicationObj.getFormMapping()[rootSheetMetadata.getSheetName()][formName]
        params={}
        params[rootSheetMetadata.getSheetName()]=getPublicCells(rootSheetMetadata)
        oneToManyList = children["root"]["OneToMany"]
        for k,v in oneToManyList.iteritems():
            referredSheetMetadata=applicationObj.getSheetMetadata(k.split('.')[1])
            params[referredSheetMetadata.getSheetName()]=getPublicCells(referredSheetMetadata,rootSheetMetadata.getSheetName())
        return params

def getXSD(session, oneToManyList,rootSheetMetadata,paramsDict,relationShipDict):
    applicationObj = session.getApplication()
    publicCells=getPublicCells(rootSheetMetadata)
    for k,v in oneToManyList.iteritems():
        referenceCellId=k.split('.')[0]
        sheetName=k.split('.')[1]
        referredSheetMetadata=applicationObj.getSheetMetadata(sheetName)
        if k in oneToManyList:
            refCellName = referredSheetMetadata.getCellMetadataById(referenceCellId).getCellName()
            newKey = refCellName+"."+sheetName
            publicCells[newKey]=sheetName
            relationShipDict[newKey]=sheetName
            currOneToManyList=oneToManyList[k]["OneToMany"]
            getXSD(session,currOneToManyList,referredSheetMetadata,paramsDict,relationShipDict)
    paramsDict[rootSheetMetadata.getSheetName()]= publicCells

def getPublicCells(metadata,parentSheetName=None):
    publicCells={}
    for k,v in sorted(metadata.getPublicCellMetadataDict().iteritems()):
        publicCells[k]= getDataType(metadata.getCellMetadataById(v))
    return publicCells

def getDataType(cellMetadata):
    dataType='string'
    category=cellMetadata.getFinalCategory()
    if category=='Category010':
        dataType='string'
    elif category=='Category010':
        dataType='string'
    elif category=='Category005':
        dataType='dateTime'
    elif category=='Category002':
        dataType='double'
    elif category=='Category001':
        dataType='string'
    return dataType