# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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.

import grpc, pytest
from typing import Tuple
from common.proto.context_pb2 import Empty
from common.proto.policy_pb2 import PolicyRuleId, PolicyRule
from context.client.ContextClient import ContextClient
#from context.client.EventsCollector import EventsCollector
from .Objects import POLICY_RULE, POLICY_RULE_ID, POLICY_RULE_UUID

def grpc_policy(
    context_client_grpc : ContextClient,                # pylint: disable=redefined-outer-name
    context_db_mb : Tuple[Database, MessageBroker]):    # pylint: disable=redefined-outer-name
    context_database = context_db_mb[0]

    # ----- Clean the database -----------------------------------------------------------------------------------------
    context_database.clear_all()

    # ----- Initialize the EventsCollector -----------------------------------------------------------------------------
    #events_collector = EventsCollector(context_client_grpc)
    #events_collector.start()

    # ----- Get when the object does not exist -------------------------------------------------------------------------
    POLICY_ID = 'no-uuid'
    DEFAULT_POLICY_ID = {'uuid': {'uuid': POLICY_ID}}

    with pytest.raises(grpc.RpcError) as e:
        context_client_grpc.GetPolicyRule(PolicyRuleId(**DEFAULT_POLICY_ID))

    assert e.value.code() == grpc.StatusCode.NOT_FOUND
    assert e.value.details() == 'PolicyRule({:s}) not found'.format(POLICY_ID)

    # ----- List when the object does not exist ------------------------------------------------------------------------
    response = context_client_grpc.ListPolicyRuleIds(Empty())
    assert len(response.policyRuleIdList) == 0

    response = context_client_grpc.ListPolicyRules(Empty())
    assert len(response.policyRules) == 0

    # ----- Dump state of database before create the object ------------------------------------------------------------
    db_entries = context_database.dump()
    LOGGER.info('----- Database Dump [{:3d} entries] -------------------------'.format(len(db_entries)))
    for db_entry in db_entries:
        LOGGER.info('  [{:>4s}] {:40s} :: {:s}'.format(*db_entry))  # pragma: no cover
    LOGGER.info('-----------------------------------------------------------')
    assert len(db_entries) == 0

    # ----- Create the object ------------------------------------------------------------------------------------------
    response = context_client_grpc.SetPolicyRule(PolicyRule(**POLICY_RULE))
    assert response.uuid.uuid == POLICY_RULE_UUID

    # ----- Check create event -----------------------------------------------------------------------------------------
    # events = events_collector.get_events(block=True, count=1)
    # assert isinstance(events[0], PolicyEvent)
    # assert events[0].event.event_type == EventTypeEnum.EVENTTYPE_CREATE
    # assert events[0].policy_id.uuid.uuid == POLICY_RULE_UUID

    # ----- Update the object ------------------------------------------------------------------------------------------
    response = context_client_grpc.SetPolicyRule(PolicyRule(**POLICY_RULE))
    assert response.uuid.uuid == POLICY_RULE_UUID

    # ----- Dump state of database after create/update the object ------------------------------------------------------
    db_entries = context_database.dump()
    LOGGER.info('----- Database Dump [{:3d} entries] -------------------------'.format(len(db_entries)))
    for db_entry in db_entries:
        LOGGER.info('  [{:>4s}] {:40s} :: {:s}'.format(*db_entry)) # pragma: no cover
    LOGGER.info('-----------------------------------------------------------')
    assert len(db_entries) == 2

    # ----- Get when the object exists ---------------------------------------------------------------------------------
    response = context_client_grpc.GetPolicyRule(PolicyRuleId(**POLICY_RULE_ID))
    assert response.device.policyRuleBasic.policyRuleId.uuid.uuid == POLICY_RULE_UUID

    # ----- List when the object exists --------------------------------------------------------------------------------
    response = context_client_grpc.ListPolicyRuleIds(Empty())
    assert len(response.policyRuleIdList) == 1
    assert response.policyRuleIdList[0].uuid.uuid == POLICY_RULE_UUID

    response = context_client_grpc.ListPolicyRules(Empty())
    assert len(response.policyRules) == 1

    # ----- Remove the object ------------------------------------------------------------------------------------------
    context_client_grpc.RemovePolicyRule(PolicyRuleId(**POLICY_RULE_ID))

    # ----- Check remove event -----------------------------------------------------------------------------------------
    # events = events_collector.get_events(block=True, count=2)

    # assert isinstance(events[0], PolicyEvent)
    # assert events[0].event.event_type == EventTypeEnum.EVENTTYPE_REMOVE
    # assert events[0].policy_id.uuid.uuid == POLICY_RULE_UUID


    # ----- Stop the EventsCollector -----------------------------------------------------------------------------------
    # events_collector.stop()

    # ----- Dump state of database after remove the object -------------------------------------------------------------
    db_entries = context_database.dump()
    LOGGER.info('----- Database Dump [{:3d} entries] -------------------------'.format(len(db_entries)))
    for db_entry in db_entries:
        LOGGER.info('  [{:>4s}] {:40s} :: {:s}'.format(*db_entry)) # pragma: no cover
    LOGGER.info('-----------------------------------------------------------')
    assert len(db_entries) == 0
