# Copyright 2022-2024 ETSI OSG/SDG TeraFlowSDN (TFS) (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.

import logging
import re
import json

from flask_restful import Resource
from werkzeug.exceptions import NotFound

from nbi.service.rest_server.nbi_plugins.tools.Authentication import HTTP_AUTH
from common.proto.acl_pb2 import AclRuleTypeEnum
from common.proto.context_pb2 import (
    ConfigActionEnum,
    ConfigRule,
    Device,
    DeviceId,
)
from common.tools.object_factory.Device import json_device_id
from common.tools.grpc.Tools import grpc_message_to_json_string
from context.client.ContextClient import ContextClient
from device.client.DeviceClient import DeviceClient


from .ietf_acl_parser import ietf_acl_from_config_rule_resource_value

LOGGER = logging.getLogger(__name__)

ACL_CONIG_RULE_KEY = r'\/device\[.+\]\/endpoint\[(.+)\]/acl_ruleset\[{}\]'


class ACL(Resource):
    # @HTTP_AUTH.login_required
    def get(self, device_uuid: str, acl_name: str):
        LOGGER.debug("GET device_uuid={:s}, acl_name={:s}".format(str(device_uuid), str(acl_name)))
        RE_ACL_CONIG_RULE_KEY = re.compile(ACL_CONIG_RULE_KEY.format(acl_name))

        context_client = ContextClient()
        device_client = DeviceClient()

        _device = context_client.GetDevice(DeviceId(**json_device_id(device_uuid)))


        for cr in _device.device_config.config_rules:
            if cr.WhichOneof('config_rule') == 'custom':
                if ep_uuid_match := RE_ACL_CONIG_RULE_KEY.match(cr.custom.resource_key):
                    endpoint_uuid = ep_uuid_match.groups(0)[0]
                    resource_value_dict = json.loads(cr.custom.resource_value)
                    LOGGER.debug(f'P99: {resource_value_dict}')
                    return ietf_acl_from_config_rule_resource_value(resource_value_dict)
        else:
            raise NotFound(f'ACL not found')

    # @HTTP_AUTH.login_required
    def delete(self, device_uuid: str, acl_name: str):
        LOGGER.debug("DELETE device_uuid={:s}, acl_name={:s}".format(str(device_uuid), str(acl_name)))
        RE_ACL_CONIG_RULE_KEY = re.compile(ACL_CONIG_RULE_KEY.format(acl_name))

        context_client = ContextClient()
        device_client = DeviceClient()

        _device = context_client.GetDevice(DeviceId(**json_device_id(device_uuid)))


        for cr in _device.device_config.config_rules:
            if cr.WhichOneof('config_rule') == 'custom':
                if ep_uuid_match := RE_ACL_CONIG_RULE_KEY.match(cr.custom.resource_key):
                    endpoint_uuid = ep_uuid_match.groups(0)[0]
                    resource_value_dict = json.loads(cr.custom.resource_value)
                    type_str = resource_value_dict['rule_set']['type']
                    interface = resource_value_dict['interface']
                    break
        else:
            raise NotFound(f'ACL not found')
        
        acl_config_rule = ConfigRule()
        acl_config_rule.action = ConfigActionEnum.CONFIGACTION_DELETE
        acl_config_rule.acl.rule_set.name = acl_name
        acl_config_rule.acl.interface = interface
        acl_config_rule.acl.rule_set.type = getattr(AclRuleTypeEnum, type_str)
        acl_config_rule.acl.endpoint_id.device_id.device_uuid.uuid = device_uuid
        acl_config_rule.acl.endpoint_id.endpoint_uuid.uuid = endpoint_uuid

        device = Device()
        device.CopyFrom(_device)
        del device.device_config.config_rules[:]
        device.device_config.config_rules.append(acl_config_rule)
        response = device_client.ConfigureDevice(device)
        return (response.device_uuid.uuid).strip("\"\n")
