# Copyright 2021-2023 H2020 TeraFlow (https://www.teraflow-h2020.eu/)
#
# 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
from datetime import datetime, timedelta
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.jobstores.memory import MemoryJobStore
from apscheduler.schedulers.blocking import BlockingScheduler
from typing import Dict
from common.proto.context_pb2 import Service, ServiceId, Slice, SliceId
from service.client.ServiceClient import ServiceClient
from slice.client.SliceClient import SliceClient
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) -> None:
        self._scheduler = BlockingScheduler()
        self._scheduler.configure(
            jobstores = {'default': MemoryJobStore()},
            executors = {'default': ThreadPoolExecutor(max_workers=10)},
            job_defaults = {
                'coalesce': False,
                'max_instances': 100,
                'misfire_grace_time': 120,
            },
            timezone=pytz.utc)
        self._parameters = parameters
        self._generator = generator

    def _schedule_request_setup(self) -> None:
        if self._generator.num_requests_generated >= self._parameters.num_requests:
            LOGGER.info('Generation Done!')
            #self._scheduler.shutdown()
            return
        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._schedule_request_setup()
        self._scheduler.start()

    def _request_setup(self) -> None:
        self._schedule_request_setup()

        request = self._generator.compose_request()
        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)

            if not self._parameters.dry_mode:
                request_add = copy.deepcopy(request)
                request_add['service_endpoint_ids'] = []
                request_add['service_constraints'] = []
                request_add['service_config'] = {'config_rules': []}
                service_client = ServiceClient()    # create instances per request to load balance between pods
                service_client.CreateService(Service(**request_add))
                service_client.UpdateService(Service(**request))
                service_client.close()

        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)

            if not self._parameters.dry_mode:
                request_add = copy.deepcopy(request)
                request_add['slice_endpoint_ids'] = []
                request_add['slice_constraints'] = []
                request_add['slice_config'] = {'config_rules': []}
                slice_client = SliceClient()    # create instances per request to load balance between pods
                slice_client.CreateSlice(Slice(**request_add))
                slice_client.UpdateSlice(Slice(**request))
                slice_client.close()

        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)

            if not self._parameters.dry_mode:
                service_client = ServiceClient()    # create instances per request to load balance between pods
                service_client.DeleteService(ServiceId(**(request['service_id'])))
                service_client.close()

        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)

            if not self._parameters.dry_mode:
                slice_client = SliceClient()    # create instances per request to load balance between pods
                slice_client.DeleteSlice(SliceId(**(request['slice_id'])))
                slice_client.close()

        self._generator.release_request(request)
