import clr
import System
clr.AddReference("System.Core")
clr.ImportExtensions(System.Linq)

clr.AddReference("RevitAPI")
clr.AddReference("RevitAPIUI")
from Autodesk.Revit.DB import *

import revit_script_util
from revit_script_util import Output

sessionId = revit_script_util.GetSessionId()
uiapp = revit_script_util.GetUIApplication()

# NOTE: these only make sense for batch Revit file processing mode.
doc = revit_script_util.GetScriptDocument()
revitFilePath = revit_script_util.GetRevitFilePath()
projectFolderName = revit_script_util.GetProjectFolderName()

# NOTE: these only make sense for data export mode.
sessionDataFolderPath = revit_script_util.GetSessionDataFolderPath()
dataExportFolderPath = revit_script_util.GetDataExportFolderPath()

# TODO: some real work!
Output()
Output("This task script is running!")

def RunBatchTaskScript(scriptFilePath):
    aborted = False

    uiapp = revit_session.GetSessionUIApplication()
    sessionId = revit_script_util.GetSessionId()
    centralFilePath = revit_script_util.GetRevitFilePath()
    openInUI = revit_script_util.GetOpenInUI()
    enableDataExport = revit_script_util.GetEnableDataExport()
    dataExportFolderPath = revit_script_util.GetDataExportFolderPath()
    showMessageBoxOnTaskError = revit_script_util.GetShowMessageBoxOnTaskError(
    )
    centralFileOpenOption = revit_script_util.GetCentralFileOpenOption()
    deleteLocalAfter = revit_script_util.GetDeleteLocalAfter()
    discardWorksetsOnDetach = revit_script_util.GetDiscardWorksetsOnDetach()
    progressNumber = revit_script_util.GetProgressNumber()
    progressMax = revit_script_util.GetProgressMax()
    output = revit_script_util.Output

    if enableDataExport and not path_util.DirectoryExists(
            dataExportFolderPath):
        output()
        output("ERROR: data export folder does not exist!")
        if not str.IsNullOrWhiteSpace(dataExportFolderPath):
            output()
            output("\t" + dataExportFolderPath)
        aborted = True
    elif not path_util.FileExists(centralFilePath):
        output()
        output("ERROR: Revit project file does not exist!")
        if not str.IsNullOrWhiteSpace(centralFilePath):
            output()
            output("\t" + centralFilePath)
        aborted = True
    else:
        if enableDataExport:
            snapshotStartTime = time_util.GetDateTimeNow()
            snapshotError = None
            snapshotEndTime = None
            revitJournalFilePath = uiapp.Application.RecordingJournalFilename
            snapshotData = snapshot_data_exporter.ExportTemporarySnapshotData(
                sessionId, centralFilePath, snapshotStartTime, snapshotEndTime,
                dataExportFolderPath, revitJournalFilePath, snapshotError)

        localFilePath = None
        openCreateNewLocal = False  # default is False because the file may not be a workshared Central file.
        isCentralModel = False
        isLocalModel = False
        try:
            output()
            output("Processing file (" + str(progressNumber) + " of " +
                   str(progressMax) + "): " + centralFilePath)

            if revit_file_util.IsWorkshared(centralFilePath):
                if revit_file_util.IsLocalModel(centralFilePath):
                    output()
                    output(
                        "WARNING: the file being processed appears to be a Workshared Local file!"
                    )
                    isLocalModel = True
                if revit_file_util.IsCentralModel(centralFilePath):
                    output()
                    output("The file is a Central Model file.")
                    isCentralModel = True
                if centralFileOpenOption == BatchRvt.CentralFileOpenOption.CreateNewLocal:
                    openCreateNewLocal = True
            elif path_util.HasFileExtension(centralFilePath, ".rfa"):
                output()
                output("The file is a Family file.")
            else:
                output()
                output("The file is a Non-workshared file.")

            if enableDataExport:
                output()
                output("Export folder is: " + dataExportFolderPath)

            def processDocument(doc):
                revit_script_util.SetScriptDocument(doc)

                def executeTaskScript():
                    success = False
                    output()
                    output("Task script operation started.")
                    if path_util.HasFileExtension(
                            scriptFilePath,
                            script_util.DYNAMO_SCRIPT_FILE_EXTENSION):
                        if revit_dynamo.IsDynamoRevitModuleLoaded():
                            revit_dynamo.ExecuteDynamoScript(uiapp,
                                                             scriptFilePath,
                                                             showUI=False)
                            success = True
                        else:
                            success = False
                            output()
                            output(revit_dynamo_error.
                                   DYNAMO_REVIT_MODULE_NOT_FOUND_ERROR_MESSAGE)
                    else:
                        script_util.ExecuteScript(scriptFilePath)
                        success = True
                    if success:
                        output()
                        output("Task script operation completed.")
                    else:
                        output()
                        output(
                            "ERROR: An error occurred while executing the task script! Operation aborted."
                        )
                    return

                result = script_host_error.WithErrorHandling(
                    executeTaskScript,
                    "ERROR: An error occurred while executing the task script! Operation aborted.",
                    output, showMessageBoxOnTaskError)
                return result

            result = None
            activeDoc = None  #revit_script_util.GetActiveDocument(uiapp)
            if activeDoc is not None:
                result = processDocument(activeDoc)
            else:
                if openCreateNewLocal:
                    revitVersion = RevitVersion.GetSupportedRevitVersion(
                        revit_session.GetSessionRevitVersionNumber())
                    localFilePath = RevitVersion.GetRevitLocalFilePath(
                        revitVersion, centralFilePath)
                    try:
                        if File.Exists(localFilePath):
                            output()
                            output("Deleting existing local file...")
                            File.Delete(localFilePath)
                            output()
                            output("Local file deleted.")
                    except Exception, e:
                        output()
                        output("WARNING: failed to delete the local file!")
                    path_util.CreateDirectoryForFilePath(localFilePath)
                    result = revit_script_util.RunNewLocalDocumentAction(
                        uiapp, openInUI, centralFilePath, localFilePath,
                        processDocument, output)
                elif isCentralModel or isLocalModel:
                    result = revit_script_util.RunDetachedDocumentAction(
                        uiapp, openInUI, centralFilePath,
                        discardWorksetsOnDetach, processDocument, output)
                else: