# 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 json, logging
from typing import Any, Dict, List, Tuple
from ._Handler import _Handler

LOGGER = logging.getLogger(__name__)

class NetworkInstanceHandler(_Handler):
    def get_resource_key(self) -> str: return '/network_instance'
    def get_path(self) -> str: return '/network-instances/network-instance'

    def compose(self, resource_key : str, resource_value : Dict, delete : bool = False) -> Tuple[str, str]:
        ni_name   = str(resource_value['name'])   # test-svc

        if delete:
            PATH_TMPL = '/network-instances/network-instance[name={:s}]'
            str_path = PATH_TMPL.format(ni_name)
            str_data = json.dumps({})
            return str_path, str_data

        ni_type   = str(resource_value['type'])   # L3VRF / L2VSI / ...

        # not works: [FailedPrecondition] unsupported identifier 'DIRECTLY_CONNECTED'
        #protocols = [self._compose_directly_connected()]

        MAP_OC_NI_TYPE = {
            'L3VRF': 'openconfig-network-instance-types:L3VRF',
        }
        ni_type = MAP_OC_NI_TYPE.get(ni_type, ni_type)

        str_path = '/network-instances/network-instance[name={:s}]'.format(ni_name)
        str_data = json.dumps({
            'name': ni_name,
            'config': {'name': ni_name, 'type': ni_type},
            #'protocols': {'protocol': protocols},
        })
        return str_path, str_data

    def _compose_directly_connected(self, name=None, enabled=True) -> Dict:
        identifier = 'DIRECTLY_CONNECTED'
        if name is None: name = 'DIRECTLY_CONNECTED'
        return {
            'identifier': identifier, 'name': name,
            'config': {'identifier': identifier, 'name': name, 'enabled': enabled},
        }

    def parse(self, json_data : Dict) -> List[Tuple[str, Dict[str, Any]]]:
        response = []
        return response
