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

"""
Returns the provided string value cast according to the provided TIBCO Spotfire Data Type.
This Data Type is generally deduced from the Data Column.
If the Data Type is not supported, None is returned.
Supported Data Types: String, Real, SingleReal, Integer, LongInteger, Date, Time, DateTime.
"""
def getCastValue(value, dataType):
    if value != None:
        if dataType == DataType.String:
            return value
        elif dataType == DataType.Real or dataType == DataType.SingleReal:
            return float(value)
        elif dataType == DataType.Integer:
            return int(value)
        elif dataType == DataType.LongInteger:
            return long(value)
        elif dataType == DataType.Date or dataType == DataType.Time or dataType == DataType.DateTime:
            return Date.Formatter.Parse(value)
    return None

def setDocumentProperty(documentPropertyName, documentPropertyValue):
    documentProperty = clr.Reference[DataProperty]()
    documentPropertyDataType = getPropertyValueDataType(documentPropertyValue)
    propertyExist = Document.Data.Properties.TryGetProperty(DataPropertyClass.Document, documentPropertyName, documentProperty);
    if (propertyExist):
        documentProperty.Value.Value = documentPropertyValue
    else:
        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)
    propertyExist = Document.Data.Properties.TryGetProperty(DataPropertyClass.Table, dataTablePropertyName, dataTableProperty)
    if(propertyExist):
        dataTable.Properties.SetProperty(dataTablePropertyName,dataTablePropertyValue)
    else:
        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
