# Copyright 2022-2023 ETSI TeraFlowSDN - TFS OSG (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, threading
from typing import Any, Iterator, List, Optional, Tuple, Union
from common.method_wrappers.Decorator import MetricsPool, metered_subclass_method
from common.type_checkers.Checkers import chk_string, chk_type
from device.service.driver_api._Driver import _Driver, RESOURCE_ENDPOINTS, RESOURCE_SERVICES
from .Tools import connection_point, find_key, wim_mapping
from .WimconnectorIETFL2VPN import WimconnectorIETFL2VPN

LOGGER = logging.getLogger(__name__)

def process_endpoint(method : str, endpoint : Any) -> Any:
    LOGGER.warning('[{:s}][process_endpoint] endpoint={:s}'.format(str(method), str(endpoint)))
    return endpoint

def process_connectivity_service(method : str, service : Any) -> Any:
    LOGGER.warning('[{:s}][process_connectivity_service] service={:s}'.format(str(method), str(service)))
    return service

def service_exists(param : Any) -> bool:
    LOGGER.warning('[service_exists] param={:s}'.format(str(param)))
    return False

ALL_RESOURCE_KEYS = [
    RESOURCE_ENDPOINTS,
    RESOURCE_SERVICES,
]

SERVICE_TYPE = 'ELINE'

METRICS_POOL = MetricsPool('Device', 'Driver', labels={'driver': 'ietf_l2vpn'})

class IetfL2VpnDriver(_Driver):
    def __init__(self, address: str, port: int, **settings) -> None:    # pylint: disable=super-init-not-called
        self.__lock = threading.Lock()
        self.__started = threading.Event()
        self.__terminate = threading.Event()
        username = settings.get('username')
        password = settings.get('password')
        scheme = settings.get('scheme', 'http')
        wim = {'wim_url': '{:s}://{:s}:{:d}'.format(scheme, address, int(port))}
        wim_account = {'user': username, 'password': password}
        # Mapping updated dynamically with each request
        config = {'mapping_not_needed': False, 'service_endpoint_mapping': []}
        self.wim = WimconnectorIETFL2VPN(wim, wim_account, config=config)
        self.conn_info = {} # internal database emulating OSM storage provided to WIM Connectors

    def Connect(self) -> bool:
        with self.__lock:
            try:
                self.wim.check_credentials()
            except Exception:  # pylint: disable=broad-except
                LOGGER.exception('Exception checking credentials')
                return False
            else:
                self.__started.set()
                return True

    def Disconnect(self) -> bool:
        with self.__lock:
            self.__terminate.set()
            return True

    @metered_subclass_method(METRICS_POOL)
    def GetInitialConfig(self) -> List[Tuple[str, Any]]:
        with self.__lock:
            return []

    @metered_subclass_method(METRICS_POOL)
    def GetConfig(self, resource_keys : List[str] = []) -> List[Tuple[str, Union[Any, None, Exception]]]:
        chk_type('resources', resource_keys, list)
        results = []
        with self.__lock:
            self.wim.check_credentials()
            if len(resource_keys) == 0: resource_keys = ALL_RESOURCE_KEYS
            for i, resource_key in enumerate(resource_keys):
                str_resource_name = 'resource_key[#{:d}]'.format(i)
                chk_string(str_resource_name, resource_key, allow_empty=False)

                if resource_key == RESOURCE_ENDPOINTS:
                    # return endpoints through debug-api and list-devices method
                    endpoints = self.debug_api.get_endpoints()
                    for endpoint in endpoints: results.append(process_endpoint('GetConfig', endpoint))
                elif resource_key == RESOURCE_SERVICES:
                    # return all services through 
                    services = self.wim.get_all_active_connectivity_services()
                    for service in services: results.append(process_connectivity_service('GetConfig', service))
                else:
                    # assume single-service retrieval
                    service = self.wim.get_connectivity_service()
                    results.append(process_connectivity_service('GetConfig', service))
        return results

    @metered_subclass_method(METRICS_POOL)
    def SetConfig(self, resources: List[Tuple[str, Any]]) -> List[Union[bool, Exception]]:
        results = []
        if len(resources) == 0: return results
        with self.__lock:
            self.wim.check_credentials()
            for resource in resources:
                LOGGER.info('resource = {:s}'.format(str(resource)))

                service_uuid = find_key(resource, 'uuid')
                a_endpoint = find_key(resource, 'a_endpoint')
                z_endpoint = find_key(resource, 'z_endpoint')
                #capacity_value = find_key(resource, 'capacity_value')
                #capacity_unit = find_key(resource, 'capacity_unit')
                #layer_protocol_name = find_key(resource, 'layer_protocol_name')
                #layer_protocol_qualifier = find_key(resource, 'layer_protocol_qualifier')
                #direction = find_key(resource, 'direction')
                encapsulation_type = find_key(resource, 'encapsulation_type')
                vlan_id = find_key(resource, 'vlan_id')

                conn_info = {}

                result = self.wim.get_connectivity_service_status(
                    service_uuid, conn_info=conn_info)

                connection_points = []
                for endpoint_id in [a_endpoint, z_endpoint]:
                    site_id = str(endpoint_id)
                    self.wim.mappings[endpoint_id] = wim_mapping(site_id, endpoint_id)
                    connection_points.append(connection_point(endpoint_id, encapsulation_type, vlan_id))
                if service_exists(result):
                    result = self.wim.create_connectivity_service(
                        SERVICE_TYPE, connection_points)
                else:
                    self.wim.edit_connectivity_service(
                        service_uuid, conn_info=conn_info, connection_points=connection_points)
                results.extend(process_connectivity_service('SetConfig', None))
        return results

    @metered_subclass_method(METRICS_POOL)
    def DeleteConfig(self, resources: List[Tuple[str, Any]]) -> List[Union[bool, Exception]]:
        results = []
        if len(resources) == 0: return results
        with self.__lock:
            self.wim.check_credentials()
            for resource in resources:
                LOGGER.info('resource = {:s}'.format(str(resource)))
                service_uuid = find_key(resource, 'uuid')

                conn_info = {}

                result = self.wim.get_connectivity_service_status(
                    service_uuid, conn_info=conn_info)
                if service_exists(result):
                    self.wim.delete_connectivity_service(
                        service_uuid, conn_info=conn_info)
                else:
                    result = False
                results.extend(process_connectivity_service('DeleteConfig', None))
        return results

    @metered_subclass_method(METRICS_POOL)
    def SubscribeState(self, subscriptions : List[Tuple[str, float, float]]) -> List[Union[bool, Exception]]:
        # TODO: IETF L2VPN does not support monitoring by now
        return [False for _ in subscriptions]

    @metered_subclass_method(METRICS_POOL)
    def UnsubscribeState(self, subscriptions : List[Tuple[str, float, float]]) -> List[Union[bool, Exception]]:
        # TODO: IETF L2VPN does not support monitoring by now
        return [False for _ in subscriptions]

    def GetState(
        self, blocking=False, terminate : Optional[threading.Event] = None
    ) -> Iterator[Tuple[float, str, Any]]:
        # TODO: IETF L2VPN does not support monitoring by now
        return []
