import subprocess
import time

from heros import DatasourceObserver

import pytest
import json
from unittest import mock
import os


class ExampleDatasource:
    _voltage: float = 0.0


@pytest.fixture()
def datasource_env():
    boss_config = json.dumps(
        {
            "_id": "test_dev_datasource",
            "classname": "src.boss.dummies.PolledDatasourceDummy",
            "arguments": {},
            "datasource": {"async": False, "interval": 1},
        }
    )
    with mock.patch.dict(os.environ, {"BOSS_DATASOURCE": boss_config}):
        yield


@mock.patch("heros.DatasourceObserver._handle_event")
def test_qcodes(event_cb, datasource_env, cleanup):
    _boss_process = subprocess.Popen(
        [
            "python",
            "-m",
            "boss.starter",
            "-e",
            "BOSS_DATASOURCE",
            "--log=debug",
            "--realm=test",
        ],
        datasource_env,
    )

    cleanup["boss"].append([_boss_process, None])
    hero = DatasourceObserver("test_dev_datasource", realm="test")
    for i in range(10):
        try:
            event_cb.assert_called()
            break
        except AssertionError:
            if i > 4:
                raise
            time.sleep(0.5)
    cleanup["heros"].append(hero)
