import copy
import grpc
import logging
import pytest
import os
import multiprocessing
from subprocess import Popen, DEVNULL
from time import sleep
from l3_distributedattackdetector.Config import GRPC_SERVICE_PORT, GRPC_MAX_WORKERS, GRPC_GRACE_PERIOD
from l3_distributedattackdetector.client.l3_distributedattackdetectorClient import l3_distributedattackdetectorClient
from l3_distributedattackdetector.service.l3_distributedattackdetectorService import l3_distributedattackdetectorService

port = 10000 + GRPC_SERVICE_PORT  # avoid privileged ports

LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(logging.DEBUG)


@pytest.fixture(scope='session')
def l3_distributedattackdetector_service():
    _service = l3_distributedattackdetectorService(
        port=port, max_workers=GRPC_MAX_WORKERS, grace_period=GRPC_GRACE_PERIOD)
    _service.start()
    yield _service
    _service.stop()


@pytest.fixture(scope='session')
def l3_distributedattackdetector_client(l3_distributedattackdetector_service):
    _client = l3_distributedattackdetectorClient(address='127.0.0.1', port=port)
    yield _client
    _client.close()


def test_demo():
    print('Demo Test')
    pass

def test_tstat():
    '''
    print('Starting DAD')
    _service = l3_distributedattackdetectorService(
        port=port, max_workers=GRPC_MAX_WORKERS, grace_period=GRPC_GRACE_PERIOD)
    p1 = multiprocessing.Process(target=_service.start, args=())
    p1.start()
    '''
    here = os.path.dirname(os.path.abspath(__file__))
    generator_filename = os.path.join(here, 'data_generator.py')
    p2 = Popen(["python3",generator_filename], stdout=DEVNULL)
    print('Started')
    sleep(15)
    #p1.terminate()
    os.system("kill %s" % (p2.pid, ))
    print('Ended Successfully')
