# 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.

import grpc, logging, os, time


from common.method_wrappers.Decorator import  MetricsPool, safe_and_metered_rpc_method

from common.proto.context_pb2 import (
   Topology,TopologyList ,TopologyId,Empty,
   Service, ServiceId , ServiceList
)

from common.proto.tapi_pb2 import TapiRequest
from common.proto.tapi_pb2_grpc import TapiService

from common.tools.mutex_queues.MutexQueues import MutexQueues
from context.client.ContextClient import ContextClient
from service.client.ServiceClient import ServiceClient
from tapi.service.tools.service_handler import process_services

LOGGER = logging.getLogger(__name__)

METRICS_POOL = MetricsPool('Tapi', 'RPC')

METRICS_POOL_DETAILS = MetricsPool('Tapi', 'execution', labels={
    'driver': '', 'operation': '', 'step': '',
})

class TapiServiceServicerImpl(TapiService):
    def __init__(self) -> None:
        LOGGER.debug('Creating Servicer...')
     
        self._ctxt = ContextClient()
        self._svc = ServiceClient()
        self.mutex_queues = MutexQueues()
        LOGGER.debug('Servicer Created')

    @safe_and_metered_rpc_method(METRICS_POOL, LOGGER)
    def GetListTopologies(self, request : Empty, context : grpc.ServicerContext) -> TopologyList:
        LOGGER.info("we recieved a request ")
        t0 = time.time()
        t1 = time.time()
        response = []
        topology_list=TopologyList()

   
        context_list = self._ctxt.ListContextIds(Empty())
        context_ids_list = context_list.context_ids
        
        
        try:
            for context_id in context_ids_list:
                topology_list = self._ctxt.ListTopologies(context_id)
                response.append(topology_list)
                
                 
            LOGGER.info(f"topologies_list {response}")
            return topology_list 
           

        except Exception as e : 
            
            LOGGER.info(f"error in Tapi servicer {e}")
    
    
    def GetTopology (self ,topology_id : TapiRequest , context : grpc.ServicerContext) -> Topology : 
        
        topology = Topology ()
        
        return topology         
    
    def SetService (self , services : ServiceList, context : grpc.ServicerContext)-> ServiceId :
        
        LOGGER.info(f"request   {services}")
        services_list = process_services(services)
        LOGGER.info(f"request   {services_list}")

        results =[]
        
        try :
            for tservice in services_list: 
                service_add,service = tservice
                LOGGER.info(f"add service   {service_add}")
                LOGGER.info(f"set service   {service}")
                service_id = self._svc.CreateService(service_add)
                if (service_id): service_id= self._svc.UpdateService(service)
                results.append(service_id)
            
            return Empty()
        except Exception as e : 
            
            LOGGER.info(f"Tapi setservice error  {e}")
        
