# 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 copy, logging, pytz, random, threading
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime, timedelta
from typing import Dict, Optional
from common.proto.context_pb2 import Service, ServiceId, Slice, SliceId
from service.client.ServiceClient import ServiceClient
from slice.client.SliceClient import SliceClient
from .Constants import MAX_WORKER_THREADS
from .DltTools import explore_entities_to_record, record_entities
from .Parameters import Parameters
from .RequestGenerator import RequestGenerator

logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING)
logging.getLogger('apscheduler.scheduler').setLevel(logging.WARNING)

LOGGER = logging.getLogger(__name__)

class RequestScheduler:
    def __init__(
        self, parameters : Parameters, generator : RequestGenerator, scheduler_class=BlockingScheduler
    ) -> None:
        self._scheduler = scheduler_class()
        self._scheduler.configure(
            jobstores = {'default': MemoryJobStore()},
            executors = {'default': ThreadPoolExecutor(max_workers=MAX_WORKER_THREADS)},
            job_defaults = {
                'coalesce': False,
                'max_instances': 100,
                'misfire_grace_time': 120,
            },
            timezone=pytz.utc)
        self._parameters = parameters
        self._generator = generator
        self._running = threading.Event()

    @property
    def num_generated(self): return min(self._generator.num_generated, self._parameters.num_requests)

    @property
    def infinite_loop(self): return self._generator.infinite_loop

    @property
    def running(self): return self._running.is_set()

    def _schedule_request_setup(self) -> None:
        iat = random.expovariate(1.0 / self._parameters.inter_arrival_time)
        run_date = datetime.utcnow() + timedelta(seconds=iat)
        self._scheduler.add_job(
            self._request_setup, trigger='date', run_date=run_date, timezone=pytz.utc)

    def _schedule_request_teardown(self, request : Dict) -> None:
        ht  = random.expovariate(1.0 / self._parameters.holding_time)
        run_date = datetime.utcnow() + timedelta(seconds=ht)
        self._scheduler.add_job(
            self._request_teardown, args=(request,), trigger='date', run_date=run_date, timezone=pytz.utc)

    def start(self):
        self._running.set()
        self._schedule_request_setup()
        self._scheduler.start()

    def stop(self):
        self._scheduler.shutdown()
        self._running.clear()

    def _request_setup(self) -> None:
        completed,request = self._generator.compose_request()
        if completed:
            LOGGER.info('Generation Done!')
            #self._scheduler.shutdown()
            self._running.clear()
            return
        else:
            self._schedule_request_setup()

        if request is None:
            LOGGER.warning('No resources available to compose new request')
            return

        if 'service_id' in request:
            service_uuid = request['service_id']['service_uuid']['uuid']
            src_device_uuid = request['service_endpoint_ids'][0]['device_id']['device_uuid']['uuid']
            src_endpoint_uuid = request['service_endpoint_ids'][0]['endpoint_uuid']['uuid']
            dst_device_uuid = request['service_endpoint_ids'][1]['device_id']['device_uuid']['uuid']
            dst_endpoint_uuid = request['service_endpoint_ids'][1]['endpoint_uuid']['uuid']
            LOGGER.info('Setup Service: uuid=%s src=%s:%s dst=%s:%s',
                service_uuid, src_device_uuid, src_endpoint_uuid, dst_device_uuid, dst_endpoint_uuid)
            self._create_update(service=request)

        elif 'slice_id' in request:
            slice_uuid = request['slice_id']['slice_uuid']['uuid']
            src_device_uuid = request['slice_endpoint_ids'][0]['device_id']['device_uuid']['uuid']
            src_endpoint_uuid = request['slice_endpoint_ids'][0]['endpoint_uuid']['uuid']
            dst_device_uuid = request['slice_endpoint_ids'][1]['device_id']['device_uuid']['uuid']
            dst_endpoint_uuid = request['slice_endpoint_ids'][1]['endpoint_uuid']['uuid']
            LOGGER.info('Setup Slice: uuid=%s src=%s:%s dst=%s:%s',
                slice_uuid, src_device_uuid, src_endpoint_uuid, dst_device_uuid, dst_endpoint_uuid)
            self._create_update(slice_=request)

        if self._parameters.do_teardown:
            self._schedule_request_teardown(request)

    def _request_teardown(self, request : Dict) -> None:
        if 'service_id' in request:
            service_uuid = request['service_id']['service_uuid']['uuid']
            src_device_uuid = request['service_endpoint_ids'][0]['device_id']['device_uuid']['uuid']
            src_endpoint_uuid = request['service_endpoint_ids'][0]['endpoint_uuid']['uuid']
            dst_device_uuid = request['service_endpoint_ids'][1]['device_id']['device_uuid']['uuid']
            dst_endpoint_uuid = request['service_endpoint_ids'][1]['endpoint_uuid']['uuid']
            LOGGER.info('Teardown Service: uuid=%s src=%s:%s dst=%s:%s',
                service_uuid, src_device_uuid, src_endpoint_uuid, dst_device_uuid, dst_endpoint_uuid)
            self._delete(service_id=ServiceId(**(request['service_id'])))

        elif 'slice_id' in request:
            slice_uuid = request['slice_id']['slice_uuid']['uuid']
            src_device_uuid = request['slice_endpoint_ids'][0]['device_id']['device_uuid']['uuid']
            src_endpoint_uuid = request['slice_endpoint_ids'][0]['endpoint_uuid']['uuid']
            dst_device_uuid = request['slice_endpoint_ids'][1]['device_id']['device_uuid']['uuid']
            dst_endpoint_uuid = request['slice_endpoint_ids'][1]['endpoint_uuid']['uuid']
            LOGGER.info('Teardown Slice: uuid=%s src=%s:%s dst=%s:%s',
                slice_uuid, src_device_uuid, src_endpoint_uuid, dst_device_uuid, dst_endpoint_uuid)
            self._delete(slice_id=SliceId(**(request['slice_id'])))

        self._generator.release_request(request)

    def _create_update(self, service : Optional[Dict] = None, slice_ : Optional[Dict] = None) -> None:
        if self._parameters.dry_mode: return

        service_id = None
        if service is not None:
            service_add = copy.deepcopy(service)
            service_add['service_endpoint_ids'] = []
            service_add['service_constraints'] = []
            service_add['service_config'] = {'config_rules': []}

            service_client = ServiceClient()
            service_id = service_client.CreateService(Service(**service_add))
            service_client.close()

        slice_id = None
        if slice_ is not None:
            slice_add = copy.deepcopy(slice_)
            slice_add['slice_endpoint_ids'] = []
            slice_add['slice_constraints'] = []
            slice_add['slice_config'] = {'config_rules': []}

            slice_client = SliceClient()
            slice_id = slice_client.CreateSlice(Slice(**slice_add))
            slice_client.close()

        if self._parameters.record_to_dlt:
            entities_to_record = explore_entities_to_record(slice_id=slice_id, service_id=service_id)
            slices_to_record, services_to_record, devices_to_record = entities_to_record
            record_entities(
                slices_to_record=slices_to_record, services_to_record=services_to_record,
                devices_to_record=devices_to_record, delete=False)

        service_id = None
        if service is not None:
            service_client = ServiceClient()
            service_id = service_client.UpdateService(Service(**service))
            service_client.close()

        slice_id = None
        if slice_ is not None:
            slice_client = SliceClient()
            slice_id = slice_client.UpdateSlice(Slice(**slice_))
            slice_client.close()

        if self._parameters.record_to_dlt:
            entities_to_record = explore_entities_to_record(slice_id=slice_id, service_id=service_id)
            slices_to_record, services_to_record, devices_to_record = entities_to_record
            record_entities(
                slices_to_record=slices_to_record, services_to_record=services_to_record,
                devices_to_record=devices_to_record, delete=False)

    def _delete(self, service_id : Optional[ServiceId] = None, slice_id : Optional[SliceId] = None) -> None:
        if self._parameters.dry_mode: return

        if self._parameters.record_to_dlt:
            entities_to_record = explore_entities_to_record(slice_id=slice_id, service_id=service_id)
            slices_to_record, services_to_record, devices_to_record = entities_to_record

        if slice_id is not None:
            slice_client = SliceClient()
            slice_client.DeleteSlice(slice_id)
            slice_client.close()

        if service_id is not None:
            service_client = ServiceClient()
            service_client.DeleteService(service_id)
            service_client.close()

        if self._parameters.record_to_dlt:
            record_entities(
                slices_to_record=slices_to_record, services_to_record=services_to_record,
                devices_to_record=devices_to_record, delete=True)
