# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (https://tfs.etsi.org/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# vary operation: create, update, delete
# vary record type (device, link, service, slice)
# for devices, services, slices, vary size: num endpoints, num constraints, num config rules
# measure load/store time
# measure event notification time

# docker build -t dlt-gateway:test -f ./src/dlt/gateway/Dockerfile .
# docker run --name dlt-gateway -d -p 50051:50051 --network=tfs-br dlt-gateway:test
# pip install grpcio==1.47.0 grpcio-tools==1.47.0 protobuf==3.20.1
# PYTHONPATH=./src python
# PYTHONPATH=./src python -m dlt.connector.tests.performance

import functools, logging, sys, time
from common.proto.dlt_gateway_pb2 import DltRecordEvent
from dlt.connector.client.DltGatewayClient import DltGatewayClient
from dlt.connector.client.DltEventsCollector import DltEventsCollector
from .play_ground.Enums import CONTEXT_EVENT_TYPE_TO_ACTION, RECORD_TYPE_TO_ENUM
from .play_ground import PlayGround

DLT_GATEWAY_HOST = '172.254.254.2'
DLT_GATEWAY_PORT = 50051

NUM_ACTIONS = 100
DOMAIN_UUID = 'perf-test-fake-domain'

CSV_FILEPATH = 'data/perf/scenario_2/dlt/2023-05May-30/response_time'

logging.basicConfig(level=logging.INFO)
LOGGER = logging.getLogger(__name__)

def _event_handler(play_ground : PlayGround, event : DltRecordEvent) -> None:
    # Filter undesired/unsupported/wrong domain_uuids, actions, and record types
    # Update notification time in PlayGround.PerfPoints
    # Return None to prevent storing the events in the DLT Events' Collector internal queue

    domain_uuid = event.record_id.domain_uuid.uuid
    if domain_uuid != DOMAIN_UUID: return None

    action = CONTEXT_EVENT_TYPE_TO_ACTION.get(event.event.event_type)
    if action is None: return None

    record_type = RECORD_TYPE_TO_ENUM.get(event.record_id.type)
    if record_type is None: return None

    #event_time = event.event.timestamp.timestamp
    record_uuid = event.record_id.record_uuid.uuid
    play_ground.perf_data.get(action, record_type, record_uuid).set_time_notified(time.time())
    return None

def main() -> None:
    dltgateway_client = DltGatewayClient(host=DLT_GATEWAY_HOST, port=DLT_GATEWAY_PORT)

    play_ground = PlayGround(dltgateway_client, DOMAIN_UUID)
    event_handler = functools.partial(_event_handler, play_ground)

    dltgateway_collector = DltEventsCollector(
        dltgateway_client, log_events_received=False, event_handler=event_handler)
    dltgateway_collector.start()

    time.sleep(3)

    LOGGER.info('Starting {:d} actions...'.format(NUM_ACTIONS))

    num_action = 0
    while num_action < NUM_ACTIONS:
        if num_action > 0 and num_action % 10 == 0:
            str_stats = play_ground.perf_data.stats_to_str()
            MSG = 'Running action {:d}/{:d}...\n{:s}'
            LOGGER.info(MSG.format(num_action, NUM_ACTIONS, str_stats))
        completed = play_ground.run_random_operation()
        if not completed: continue
        num_action += 1

    LOGGER.info('Completed {:d} actions!'.format(NUM_ACTIONS))

    dltgateway_collector.stop()

    play_ground.perf_data.to_csv(CSV_FILEPATH)
    return 0

if __name__ == '__main__':
    sys.exit(main())
