# Copyright 2022-2024 ETSI 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.


# WARNING: this handler is work in progress. Use with care!

import logging, json
from typing import Any, Dict, List, Tuple

LOGGER = logging.getLogger(__name__)

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

    def compose_set(self, resource_key : str, resource_value : Dict) -> Tuple[str, str]:
        ni_name = str(resource_value['name'])   # test-svc
        ni_type = str(resource_value['type'])   # L3VRF / 

        if_name          = str (resource_value['name'                         ])    # ethernet-1/1
        if_enabled       = bool(resource_value.get('enabled'            , True))    # True/False
        sif_index        = int (resource_value.get('sub_if_index'       , 0   ))    # 0
        sif_enabled      = bool(resource_value.get('sub_if_enabled'     , True))    # True/False
        sif_ipv4_enabled = bool(resource_value.get('sub_if_ipv4_enabled', True))    # True/False
        sif_ipv4_address = str (resource_value['sub_if_ipv4_address'          ])    # 172.16.0.1
        sif_ipv4_prefix  = int (resource_value['sub_if_ipv4_prefix'           ])    # 24

        str_path = '/interfaces/interface[name={:s}]'.format(if_name)
        str_data = json.dumps({
            "name": if_name,
            "config": {"name": if_name, "enabled": if_enabled},
            "subinterfaces": {
                "subinterface": {
                    "index": sif_index,
                    "config": {"index": sif_index, "enabled": sif_enabled},
                    "ipv4": {
                        "config": {"enabled": sif_ipv4_enabled},
                        "addresses": {
                            "address": {
                                "ip": sif_ipv4_address,
                                "config": {"ip": sif_ipv4_address, "prefix_length": sif_ipv4_prefix},
                            }
                        }
                    }
                }
            }
        })
        return str_path, str_data


        #oc_ni = openconfig_network_instance()
        #ni = oc_ni.network_instances.network_instance.add(name=ni_name)
        #ni.config.name = ni_name

        #ni_desc = resource_value.get('description')
        #if ni_desc is not None: ni.config.description = ni_desc

        #if ni_type == 'L3VRF':
        #    ni.config.type = 'L3VRF'
        #    #ni_router_id  = resource_value.get('router_id')
        #    #if ni_router_id is not None: ni.config.router_id = ni_router_id

        #    proto_bgp = ni.protocols.protocol.add(identifier='BGP', name=ni_name)
        #    proto_bgp.config.identifier = 'BGP'
        #    proto_bgp.config.name = ni_name
        #    proto_bgp.config.enabled = True
        #    proto_bgp.bgp.global_.config.as_ = 65000
        #    proto_bgp.bgp.global_.config.router_id = '172.0.0.1'

        #    #ni.config.route_distinguisher = resource_value['route_distinguisher']
        #elif ni_type == 'L3VRF':
        #    pass
        #else:
        #    raise NotImplementedError()
        
        #str_path = '/network-instances/network-instance[name={:s}]'.format(ni_name)
        #str_data = pybindJSON.dumps(ni, mode='default')

        #str_path = '/network-instances/network-instance[name={:s}]/protocols/protocol[identifier=BGP][name=BGP]'.format(ni_name)
        #str_data = json.dumps({
        #    "identifier": "BGP",
        #    "name": "BGP",
        #    "config": {"identifier": "BGP", "name": "BGP", "enabled": True},
        #    "bgp": {"global": {"config": {"as": 65000, "router-id": "5.5.5.5"}}}
        #})

        str_path = '/network-instances/network-instance[name=test-svc]'
        str_data = json.dumps({
            "name": "test-svc",
            "config": {
                "name": "test-svc",
                "type": "openconfig-network-instance-types:L3VRF"
            },
            "protocols": {
                "protocol": [
                    {
                        "identifier": "DIRECTLY_CONNECTED",
                        "name": "DIRECTLY-CONNECTED",
                        "config": {"identifier": "DIRECTLY_CONNECTED", "name": "DIRECTLY-CONNECTED", "enabled": True},
                    },
                    {
                        "identifier": "STATIC",
                        "name": "static",
                        "config": {"identifier": "STATIC", "name": "static", "enabled": True},
                        "static_routes": {
                            "static": [
                                {
                                    "prefix": "172.0.1.0/24",
                                    "config": {"prefix": "172.0.1.0/24"},
                                    "next_hops": {
                                        "next-hop": [{"index": 0, "config": {"index": 0, "next_hop": "172.0.0.1"}}]
                                    }
                                }
                            ]
                        }
                    }
                ]
            },
        })


        #str_path = '/network-instances/network-instance[name={:s}]/protocols/protocol[identifier=DIRECTLY_CONNECTED][name=DIR]'.format(ni_name)
        #str_data = json.dumps({
        #    "identifier": "DIRECTLY_CONNECTED",
        #    "name": "DIR",
        #    "config": {"identifier": "DIRECTLY_CONNECTED", "name": "DIR", "enabled": True},
        #})
