# 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
from service.client.ServiceClient import ServiceClient
from .Parameters import Parameters
from .ServiceGenerator import ServiceGenerator

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

LOGGER = logging.getLogger(__name__)

class ServiceScheduler:
    def __init__(self, parameters : Parameters, service_generator : ServiceGenerator) -> 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._service_generator = service_generator

    def _schedule_service_setup(self) -> None:
        if self._service_generator.num_services_generated >= self._parameters.num_services:
            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._service_setup, trigger='date', run_date=run_date, timezone=pytz.utc)

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

    def start(self):
        self._schedule_service_setup()
        self._scheduler.start()

    def _service_setup(self) -> None:
        self._schedule_service_setup()

        service = self._service_generator.compose_service()
        if service is None:
            LOGGER.warning('No resources available to compose new service')
            return

        service_uuid = service['service_id']['service_uuid']['uuid']
        src_device_uuid = service['service_endpoint_ids'][0]['device_id']['device_uuid']['uuid']
        src_endpoint_uuid = service['service_endpoint_ids'][0]['endpoint_uuid']['uuid']
        dst_device_uuid = service['service_endpoint_ids'][1]['device_id']['device_uuid']['uuid']
        dst_endpoint_uuid = service['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:
            service_add = copy.deepcopy(service)
            service_add['service_endpoint_ids'] = []
            service_add['service_constraints'] = []
            service_add['service_config'] = {'config_rules': []}
            service_client = ServiceClient()    # create instances per request to load balance between pods
            service_client.CreateService(Service(**service_add))
            service_client.UpdateService(Service(**service))

        self._schedule_service_teardown(service)

    def _service_teardown(self, service : Dict) -> None:
        service_uuid = service['service_id']['service_uuid']['uuid']
        src_device_uuid = service['service_endpoint_ids'][0]['device_id']['device_uuid']['uuid']
        src_endpoint_uuid = service['service_endpoint_ids'][0]['endpoint_uuid']['uuid']
        dst_device_uuid = service['service_endpoint_ids'][1]['device_id']['device_uuid']['uuid']
        dst_endpoint_uuid = service['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(**(service['service_id'])))

        self._service_generator.release_service(service)
