from paraview.simple import *
from paraview import live

"""
This example demonstrates how to use python to connect to a Catalyst session.

At each timestep, the slice is extracted and a non-interactive render view
is updated. When the connection is closed (due to simulation end),
the interaction is enabled in the view.

First make sure that LiveVisualization is enabled in the script. Then run this example.
Last run the simulation.

For instance:
    modify Examples/Catalyst/CxxFullExample/SampleScripts/feslicescript.py
    ```
    coprocessor.EnableLiveVisualization(True)
    ```
    Then run:
    ```
    $ pvpython catalystLiveVisualizer.py
    $ ./CxxFullExample feslicescript.py
    ```
"""

# ----------------------------
# misc callbacks
# ----------------------------
def _updateEventCb(obj, event):
    print("Update event received.")

def _connectionCreatedCb(obj, event):
    print("Connection created")

def _connectionClosedCb(obj, event):
    global ProcessEvents
    ProcessEvents = False
    print("Connection closed, interaction enabled.\nPress 'q' to quit.")
    Interact()
    print("Exit.")


# ----------------------------
# Utilities methods
# ----------------------------
def _monitorServerNotifications():
    import threading
    global ProcessEvents
    ProcessEvents = True
    live.ProcessServerNotifications()
    print("waiting...")
    if ProcessEvents:
        threading.Timer(.2, _monitorServerNotifications).start()


DataExtracted = False

# ----------------------------
# Create the catalyst connection
liveInsituLink = live.ConnectToCatalyst()
liveInsituLink.AddObserver("UpdateEvent", _updateEventCb)
liveInsituLink.AddObserver("ConnectionCreatedEvent", _connectionCreatedCb)
liveInsituLink.AddObserver("ConnectionClosedEvent", _connectionClosedCb)

# ----------------------------
# Automatically look for updates
_monitorServerNotifications()
