def getToolPath(toolName, toolVersion):
    directory = Directory.GetCurrentDirectory()
    importDirectory = Path.GetDirectoryName(directory)
    return importDirectory + toolName + toolVersion

def appendToAssemblyPath(toolName, toolVersion):
    sys.path.append(getToolPath(toolName, toolVersion))

def createConditionalValue(conditionType, value):
    conditionValue = None
    if(conditionType == 'MinValue'):
        conditionValue = ConditionValue.MinValue
    elif (conditionType == 'MaxValue'):
        conditionValue = ConditionValue.MaxValue
    elif (conditionType == 'MedianValue'):
        conditionValue = ConditionValue.MedianValue
    elif (conditionType == 'AverageValue'):
        conditionValue = ConditionValue.AverageValue
    elif (conditionType == 'Literal'):
        conditionValue = ConditionValue.CreateLiteral(value)
    elif (conditionType == 'Percent'):
        if (type(value) != float):
            value = float(value)
        conditionValue = ConditionValue.CreatePercentValue(value)
    elif (conditionType == 'Percentile'):
        if (type(value) != float):
            value = float(value)
        conditionValue = ConditionValue.CreatePercentileValue(value)
    elif (conditionType == 'Expression'):
        conditionValue = ConditionValue.CreateExpression(value)
    return conditionValue

def getValueRendererType(typeLabel):
    rendererType = ValueRendererTypeIdentifiers.DefaultRenderer
    if(typeLabel == 'Link'):
        rendererType = ValueRendererTypeIdentifiers.LinkRenderer
    elif(typeLabel == 'Image from URL'):
        rendererType = ValueRendererTypeIdentifiers.ImageFromUrlRenderer
    elif(typeLabel == 'Image'):
        rendererType = ValueRendererTypeIdentifiers.BitmapRenderer
    return rendererType

def getDataSource(sourcePathOrUrl):
    dataSource = None
    extension = None
    request = WebRequest.Create(sourcePathOrUrl)
    downloadStream = request.GetResponse()
    extensionRegexp = re.compile('.*\.([a-zA-Z0-9]+)$')
    match = extensionRegexp.match(sourcePathOrUrl)
    if len(match.groups()) > 0:
        extension = String.ToLower(match.group(1))
    if(extension == 'sbdf'):
        dataSource = SbdfFileDataSource(downloadStream.GetResponseStream())
    elif(extension == 'stdf'):
        dataSource = StdfFileDataSource(downloadStream.GetResponseStream())
    elif(extension != None):
        dataSource = TextFileDataSource(downloadStream.GetResponseStream())
    downloadStream.Close()
    return dataSource

def serializeToJSON(objectToSerialize):
    serializer = JavaScriptSerializer()
    return serializer.Serialize(objectToSerialize)

def deserializeFromJSON(jsonString):
    serializer = JavaScriptSerializer()
    return serializer.DeserializeObject(jsonString)

def getPropertyValueDataType(value):
    dataType = DataType.String
    if(type(value) == str):
        dataType = DataType.String
    elif(type(value) == int):
        dataType = DataType.Integer
    elif(type(value) == float):
        dataType = DataType.Real
    elif(type(value) == bool):
        dataType = DataType.Boolean
    elif(type(value) == long):
        dataType = DataType.LongInteger
    elif(type(value) == datetime):
        dataType = DataType.DateTime
    elif(type(value) == timedelta):
        dataType = DataType.TimeSpan
    return dataType

def setDocumentProperty(documentPropertyName, documentPropertyValue):
    documentProperty = clr.Reference[DataProperty]()
    documentPropertyDataType = getPropertyValueDataType(documentPropertyValue)
    if(Document.Data.Properties.TryGetProperty(DataPropertyClass.Document, documentPropertyName, documentProperty)):
        Document.Data.Properties.RemoveProperty(DataPropertyClass.Document, documentPropertyName)
    documentProperty.Value = DataProperty.CreateCustomPrototype(documentPropertyName, documentPropertyDataType, DataProperty.DefaultAttributes)
    Document.Data.Properties.AddProperty(DataPropertyClass.Document, documentProperty.Value)
    documentProperty.Value.Value = documentPropertyValue

def setDataTableProperty(dataTable, dataTablePropertyName, dataTablePropertyValue):
    dataTableProperty = clr.Reference[DataProperty]()
    dataTablePropertyDataType = getPropertyValueDataType(dataTablePropertyValue)
    if(Document.Data.Properties.TryGetProperty(DataPropertyClass.Table, dataTablePropertyName, dataTableProperty)):
        Document.Data.Properties.RemoveProperty(DataPropertyClass.Table, dataTablePropertyName)
    dataTableProperty.Value = DataProperty.CreateCustomPrototype(dataTablePropertyName, dataTablePropertyDataType, DataProperty.DefaultAttributes)
    Document.Data.Properties.AddProperty(DataPropertyClass.Table, dataTableProperty.Value)
    dataTable.Properties.SetProperty(dataTablePropertyName,dataTablePropertyValue)

def containsKey(searchKey, dictionary):
    for key in dictionary.Keys:
        if(key == searchKey):
            return True
    return False

def setResultProperty(objectAsJSONString):
    global resultPropertyName
    result = {}
    result[resultPropertyName] = ''
    resultByExecution = {};
    documentResultProperty = clr.Reference[DataProperty]()
    if(Document.Data.Properties.TryGetProperty(DataPropertyClass.Document, resultPropertyName, documentResultProperty)):
        tempResult = deserializeFromJSON(documentResultProperty.Value.Value)
        if type(tempResult) is dict and containsKey(resultPropertyName, tempResult):
            result = tempResult
            resultByExecution = deserializeFromJSON(result[resultPropertyName])
    resultByExecution[jsonParam['executionGuid']] = objectAsJSONString
    result[resultPropertyName] = serializeToJSON(resultByExecution)
    resultAsJSONString = serializeToJSON(result)
    setDocumentProperty(resultPropertyName, resultAsJSONString)

def getStreamFromUrl(fileUrl):
    request = WebRequest.Create(fileUrl)
    return request.GetResponse().GetResponseStream()

def getColorSchemeFromLibrary(libraryColorSchemePath):
    libraryManager = Application.GetService(LibraryManager)
    success,libraryItem = libraryManager.TryGetItem(libraryColorSchemePath,LibraryItemType.ColorScheme)
    if not success:
        raise ApplicationException('the color scheme \"' + libraryColorSchemePath + '\" doesn\'t exists.')
    return libraryItem

def createRecursiveFolder(fullPath):
    libraryManager = Application.GetService(LibraryManager)

def save(app):
   def f():
      app.Save()
   return f

def saveAsLibraryItem(app, folder, fileName, metaData, saveSettings):
   def f():
      app.SaveAs(folder, fileName, metaData, saveSettings)
   return f

def saveAsLocal(app, folderName, fileName, saveSettings):
	def f():
		fullPath = folderName + fileName
		app.SaveAs(fullPath, saveSettings)
	return f

global resultPropertyName

resultPropertyName = jsonParam['returnProperty']
notificationLabel = jsonParam['notificationLabel']
errorPropertyName = jsonParam['errorProperty']

setDocumentProperty(errorPropertyName, '')
notify = Application.GetService[NotificationService]()

pageToModify = Document.ActivePageReference
currentDataTable = None
dataviz = None
