import asyncio

from parat.services import ApplyController, ParaT, PipelineBuilder, PipelineViewer


recordedConnectivities = []
expectedConnectivities = [
    [],
    [("Wavelet1", [])],
    [("Wavelet1", []), ("Wavelet2", [])],
    [("Wavelet1", []), ("Wavelet2", []), ("Contour1", ["Wavelet1"])],
    [
        ("Wavelet1", []),
        ("Wavelet2", []),
        ("Contour1", ["Wavelet1"]),
        ("Clip1", ["Contour1"]),
    ],
    [
        ("Wavelet1", []),
        ("Wavelet2", []),
        ("Contour1", ["Wavelet1"]),
        ("Clip1", ["Contour1"]),
        ("Clip2", ["Wavelet2"]),
    ],
]


async def observer_pipeline(pipelineViewer):
    global recordedConnectivities
    async for pipelineState in pipelineViewer.GetObservable():
        connectivity = []
        for item in pipelineState:
            name = item.GetName()
            parentNames = []
            for i in item.GetParentIDs():
                parentProxy = pipelineViewer.GetSession().GetProxyManager().FindProxy(i)
                parentNames = [parentProxy.GetLogName()]
            connectivity.append((name, parentNames))
        recordedConnectivities.append(connectivity)


async def main():
    App = ParaT()
    session = await App.initialize()
    builder = PipelineBuilder(session)
    pipelineViewer = PipelineViewer(session)
    task = asyncio.create_task(observer_pipeline(pipelineViewer))

    wavelet = await builder.CreateProxy("sources", "RTAnalyticSource")
    wavelet2 = await builder.CreateProxy("sources", "RTAnalyticSource")

    contour = await builder.CreateProxy("filters", "Contour", Input=wavelet)
    await builder.CreateProxy("filters", "Clip", Input=contour)
    await builder.CreateProxy("filters", "Clip", Input=wavelet2)

    pipelineViewer.UnsubscribeAll()
    await task
    assert recordedConnectivities == expectedConnectivities
    await App.finalize()


asyncio.run(main())
