# 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
from typing import Dict
from flask import request
from flask_restful import Resource
from werkzeug.exceptions import NotFound, UnsupportedMediaType
from common.proto.context_pb2 import Device, DeviceId
from common.tools.grpc.Tools import grpc_message_to_json_string
from common.tools.object_factory.Device import json_device_id
from context.client.ContextClient import ContextClient
from device.client.DeviceClient import DeviceClient
#from nbi.service.rest_server.nbi_plugins.tools.Authentication import HTTP_AUTH
from .ietf_acl_parser import config_rule_from_ietf_acl

LOGGER = logging.getLogger(__name__)

class ACLs(Resource):
    # @HTTP_AUTH.login_required
    def get(self):
        return {}

    # @HTTP_AUTH.login_required
    def post(self, device_uuid: str):
        LOGGER.debug("POST device_uuid={:s}, body={:s}".format(str(device_uuid), str(request.data)))
        if not request.is_json:
            raise UnsupportedMediaType("JSON pyload is required")
        request_data: Dict = request.json
        LOGGER.debug("Request: {:s}".format(str(request_data)))
        attached_interface = request_data["ietf-access-control-list"]["acls"]['attachment-points']['interface'][0]['interface-id']

        context_client = ContextClient()
        device_client = DeviceClient()

        _device = context_client.GetDevice(DeviceId(**json_device_id(device_uuid)))
        
        for ep in _device.device_endpoints:
            if ep.name == attached_interface:
                endpoint_uuid = ep.endpoint_id.endpoint_uuid.uuid
                break
        else:
            raise NotFound(f'interface {attached_interface} not found in device {device_uuid}')

        acl_config_rule = config_rule_from_ietf_acl(request_data, device_uuid, endpoint_uuid, sequence_id=1, subinterface=0)

        LOGGER.info(f"ACL Config Rule: {grpc_message_to_json_string(acl_config_rule)}")

        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")
