# Copyright 2022-2024 ETSI OSG/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 logging
from typing import Optional

import requests
from requests.auth import HTTPBasicAuth

IETF_SLICE_URL = "{:s}://{:s}:{:d}/restconf/data/ietf-network-slice-service"
TIMEOUT = 30

LOGGER = logging.getLogger(__name__)

HEADERS = {'Content-Type': 'application/json'}


class TfsApiClient:
    def __init__(
        self,
        address: str,
        port: int,
        scheme: str = "http",
        username: Optional[str] = None,
        password: Optional[str] = None,
    ) -> None:
        self._slice_url = IETF_SLICE_URL.format(scheme, address, port)
        self._auth = None
        # (
        #     HTTPBasicAuth(username, password)
        #     if username is not None and password is not None
        #     else None
        # )

    def create_slice(self, slice_data: dict) -> None:
        url = self._slice_url + ":network-slice-services"
        try:
            requests.post(url, json=slice_data, headers=HEADERS)
        except requests.exceptions.ConnectionError:
            raise Exception("faild to send post request to TFS IETF Slice NBI")

    def update_slice(
        self,
        slice_name: str,
        connection_group_id: str,
        updated_connection_group_data: dict,
    ) -> None:
        url = (
            self._slice_url
            + f":network-slice-services/slice-service={slice_name}/connection-groups/connection-group={connection_group_id}"
        )
        try:
            requests.put(url, json=updated_connection_group_data, headers=HEADERS)
        except requests.exceptions.ConnectionError:
            raise Exception("faild to send update request to TFS IETF Slice NBI")

    def delete_slice(self, slice_name: str) -> None:
        url = self._slice_url + f":network-slice-services/slice-service={slice_name}"
        try:
            requests.delete(url)
        except requests.exceptions.ConnectionError:
            raise Exception("faild to send delete request to TFS IETF Slice NBI")
