# -*- mode: python -*-

from contextlib import contextmanager, ExitStack

from tests.conftest import create_rmr_network_space  # pylint: disable=import-error, no-name-in-module
from infinisdk.infinibox import InfiniBox
from infinisim.infinibox import Infinibox as Simulator
from waiting import wait

_AUTH = ('infinidat', '123456')

@contextmanager
def _system():
    simulator = Simulator()

    simulator.activate()
    try:
        system = InfiniBox(simulator, auth=_AUTH)
        system.login()
        yield system
    finally:
        simulator.deactivate()

@contextmanager
def doctest_context():

    with ExitStack() as stack:

        primary_system = stack.enter_context(_system())
        secondary_system = stack.enter_context(_system())

        primary_ns = create_rmr_network_space(primary_system)
        secondary_ns = create_rmr_network_space(secondary_system)

        link = primary_system.links.create(
            name='link',
            local_replication_network_space_id=primary_ns.id,
            remote_host=secondary_ns.get_mgmt_ip().ip_address,
        )

        vol = primary_system.volumes.create(pool=primary_system.pools.create())
        async_replica = primary_system.replicas.replicate_entity(
            vol, link=link, remote_pool=secondary_system.pools.create())
        wait(async_replica.is_idle)

        yield {
            'link': link,
            'primary_system': primary_system,
            'primary_ip': primary_ns.get_mgmt_ip(),
            'secondary_system': secondary_system,
            'secondary_ip': secondary_ns.get_mgmt_ip(),
            'async_replica': async_replica,
        }
