# 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 logging
from typing import Dict, List
from flask import request
from flask.json import jsonify
from flask_restful import Resource
from werkzeug.exceptions import UnsupportedMediaType
from common.Constants import DEFAULT_CONTEXT_UUID
from common.proto.context_pb2 import Service, ServiceStatusEnum, ServiceTypeEnum, SliceStatusEnum, Slice
from service.client.ServiceClient import ServiceClient
from slice.client.SliceClient import SliceClient
from .schemas.vpn_service import SCHEMA_VPN_SERVICE
from .tools.Authentication import HTTP_AUTH
from .tools.HttpStatusCodes import HTTP_CREATED, HTTP_SERVERERROR
from .tools.Validator import validate_message

LOGGER = logging.getLogger(__name__)

class L2VPN_Services(Resource):
    @HTTP_AUTH.login_required
    def get(self):
        return {}

    @HTTP_AUTH.login_required
    def post(self):
        if not request.is_json: raise UnsupportedMediaType('JSON payload is required')
        request_data : Dict = request.json
        LOGGER.debug('Request: {:s}'.format(str(request_data)))
        validate_message(SCHEMA_VPN_SERVICE, request_data)

        vpn_services : List[Dict] = request_data['ietf-l2vpn-svc:vpn-service']
        for vpn_service in vpn_services:
            try:
                # By now, assume requests from OSM always need transport slices
                # TODO: think how to differentiate
                #vpn_service_type = vpn_service['vpn-svc-type']
                vpn_service_type = 'vpls'

                if vpn_service_type == 'vpws':
                    # pylint: disable=no-member
                    service_request = Service()
                    service_request.service_id.context_id.context_uuid.uuid = DEFAULT_CONTEXT_UUID
                    service_request.service_id.service_uuid.uuid = vpn_service['vpn-id']
                    service_request.service_type = ServiceTypeEnum.SERVICETYPE_L3NM
                    service_request.service_status.service_status = ServiceStatusEnum.SERVICESTATUS_PLANNED

                    service_client = ServiceClient()
                    service_reply = service_client.CreateService(service_request)
                    if service_reply != service_request.service_id: # pylint: disable=no-member
                        raise Exception('Service creation failed. Wrong Service Id was returned')
                elif vpn_service_type == 'vpls':
                    # pylint: disable=no-member
                    slice_request = Slice()
                    slice_request.slice_id.context_id.context_uuid.uuid = DEFAULT_CONTEXT_UUID
                    slice_request.slice_id.slice_uuid.uuid = vpn_service['vpn-id']
                    slice_request.slice_status.slice_status = SliceStatusEnum.SLICESTATUS_PLANNED

                    slice_client = SliceClient()
                    slice_reply = slice_client.CreateSlice(slice_request)
                    if slice_reply != slice_request.slice_id: # pylint: disable=no-member
                        raise Exception('Slice creation failed. Wrong Slice Id was returned')

                response = jsonify({})
                response.status_code = HTTP_CREATED
            except Exception as e: # pylint: disable=broad-except
                LOGGER.exception('Something went wrong Creating Service {:s}'.format(str(request)))
                response = jsonify({'error': str(e)})
                response.status_code = HTTP_SERVERERROR
        return response
