# coding: utf-8

"""
    VNS3 Controller API

    Cohesive networks VNS3 API providing complete control of your network's addresses, routes, rules and edge  # noqa: E501

    The version of the OpenAPI document: 4.8
    Contact: solutions@cohesive.net
    Generated by: https://openapi-generator.tech
"""


from __future__ import absolute_import

import re  # noqa: F401

# python 2 and python 3 compatibility library
import six

from cohesivenet import Logger
from cohesivenet.exceptions import ApiTypeError, ApiValueError


class RouteConstants(object):
    RouteComparisonKeys = ["cidr", "interface", "gateway"]


class RoutingApi(object):
    """NOTE: This class is auto generated by OpenAPI Generator
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    def __init__(self, api_client=None):
        if api_client is None:
            from cohesivenet.vns3_client import VNS3Client

            api_client = VNS3Client()
        self.api_client = api_client

    def delete_route(self, route_id, **kwargs):  # noqa: E501
        """delete_route  # noqa: E501

        Delete Route  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.delete_route(route_id, async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param int route_id: ID for Route (required)
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: RoutesListResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs["_return_http_data_only"] = True
        return self.delete_route_with_http_info(route_id, **kwargs)  # noqa: E501

    def delete_route_with_http_info(self, route_id, **kwargs):  # noqa: E501
        """delete_route  # noqa: E501

        Delete Route  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.delete_route_with_http_info(route_id, async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param int route_id: ID for Route (required)
        :param _return_http_data_only: response data without head status code
                                       and headers
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: tuple(RoutesListResponse, status_code(int), headers(HTTPHeaderDict))
                 If the method is called asynchronously,
                 returns the request thread.
        """

        local_var_params = locals()

        all_params = ["route_id"]  # noqa: E501
        all_params.append("async_req")
        all_params.append("_return_http_data_only")
        all_params.append("_preload_content")
        all_params.append("_request_timeout")

        for key, val in six.iteritems(local_var_params["kwargs"]):
            if key not in all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method delete_route" % key
                )
            local_var_params[key] = val
        del local_var_params["kwargs"]
        # verify the required parameter 'route_id' is set
        if "route_id" not in local_var_params or local_var_params["route_id"] is None:
            raise ApiValueError(
                "Missing the required parameter `route_id` when calling `delete_route`"
            )  # noqa: E501

        if (
            "route_id" in local_var_params and local_var_params["route_id"] < 0
        ):  # noqa: E501
            raise ApiValueError(
                "Invalid value for parameter `route_id` when calling `delete_route`, must be a value greater than or equal to `0`"
            )  # noqa: E501
        collection_formats = {}

        path_params = {}
        if "route_id" in local_var_params:
            path_params["route_id"] = local_var_params["route_id"]  # noqa: E501

        query_params = []

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params["Accept"] = self.api_client.select_header_accept(
            ["application/json"]
        )  # noqa: E501

        # Authentication setting
        auth_settings = ["basicAuth"]  # noqa: E501

        return self.api_client.call_api(
            "/routes/{route_id}",
            "DELETE",
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_type="RoutesListResponse",  # noqa: E501
            auth_settings=auth_settings,
            async_req=local_var_params.get("async_req"),
            _return_http_data_only=local_var_params.get(
                "_return_http_data_only"
            ),  # noqa: E501
            _preload_content=local_var_params.get("_preload_content", True),
            _request_timeout=local_var_params.get("_request_timeout"),
            collection_formats=collection_formats,
        )

    def get_routes(self, **kwargs):  # noqa: E501
        """get_routes  # noqa: E501

        Describes routes that this manager has access to via its network interfaces (virtual or otherwise).  If advertized, other VNS3 Controllers will receive the route instantly. Network clients will  receive it when they get their next route push, which is normally on a re-connect or in neartime  if they use the VNS3 Routing agent on their cloud servers. Remote endpoints  (other data centers) would not receive the route unless specified as part of  their IPsec Configuration AND the Configuration of such a tunnel on the VNS3 controller.   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.get_routes(async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: RoutesListResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs["_return_http_data_only"] = True
        return self.get_routes_with_http_info(**kwargs)  # noqa: E501

    def get_routes_with_http_info(self, **kwargs):  # noqa: E501
        """get_routes  # noqa: E501

        Describes routes that this manager has access to via its network interfaces (virtual or otherwise).  If advertized, other VNS3 Controllers will receive the route instantly. Network clients will  receive it when they get their next route push, which is normally on a re-connect or in neartime  if they use the VNS3 Routing agent on their cloud servers. Remote endpoints  (other data centers) would not receive the route unless specified as part of  their IPsec Configuration AND the Configuration of such a tunnel on the VNS3 controller.   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.get_routes_with_http_info(async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param _return_http_data_only: response data without head status code
                                       and headers
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: tuple(RoutesListResponse, status_code(int), headers(HTTPHeaderDict))
                 If the method is called asynchronously,
                 returns the request thread.
        """

        local_var_params = locals()

        all_params = []  # noqa: E501
        all_params.append("async_req")
        all_params.append("_return_http_data_only")
        all_params.append("_preload_content")
        all_params.append("_request_timeout")

        for key, val in six.iteritems(local_var_params["kwargs"]):
            if key not in all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method get_routes" % key
                )
            local_var_params[key] = val
        del local_var_params["kwargs"]

        collection_formats = {}

        path_params = {}

        query_params = []

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params["Accept"] = self.api_client.select_header_accept(
            ["application/json"]
        )  # noqa: E501

        # Authentication setting
        auth_settings = ["basicAuth"]  # noqa: E501

        return self.api_client.call_api(
            "/routes",
            "GET",
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_type="RoutesListResponse",  # noqa: E501
            auth_settings=auth_settings,
            async_req=local_var_params.get("async_req"),
            _return_http_data_only=local_var_params.get(
                "_return_http_data_only"
            ),  # noqa: E501
            _preload_content=local_var_params.get("_preload_content", True),
            _request_timeout=local_var_params.get("_request_timeout"),
            collection_formats=collection_formats,
        )

    def post_create_route(self, create_route_request, **kwargs):  # noqa: E501
        """post_create_route  # noqa: E501

        Pushes routes that this manager has access to via its network interfaces (virtual or otherwise)   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.post_create_route(create_route_request, async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param CreateRouteRequest create_route_request: (required)
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: RoutesListResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs["_return_http_data_only"] = True
        return self.post_create_route_with_http_info(
            create_route_request, **kwargs
        )  # noqa: E501

    def post_create_route_with_http_info(
        self, create_route_request, **kwargs
    ):  # noqa: E501
        """post_create_route  # noqa: E501

        Pushes routes that this manager has access to via its network interfaces (virtual or otherwise)   # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.post_create_route_with_http_info(create_route_request, async_req=True)
        >>> result = thread.get()

        :param async_req bool: execute request asynchronously
        :param CreateRouteRequest create_route_request: (required)
        :param _return_http_data_only: response data without head status code
                                       and headers
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: tuple(RoutesListResponse, status_code(int), headers(HTTPHeaderDict))
                 If the method is called asynchronously,
                 returns the request thread.
        """

        local_var_params = locals()

        all_params = ["create_route_request"]  # noqa: E501
        all_params.append("async_req")
        all_params.append("_return_http_data_only")
        all_params.append("_preload_content")
        all_params.append("_request_timeout")

        for key, val in six.iteritems(local_var_params["kwargs"]):
            if key not in all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method post_create_route" % key
                )
            local_var_params[key] = val
        del local_var_params["kwargs"]
        # verify the required parameter 'create_route_request' is set
        if (
            "create_route_request" not in local_var_params
            or local_var_params["create_route_request"] is None
        ):
            raise ApiValueError(
                "Missing the required parameter `create_route_request` when calling `post_create_route`"
            )  # noqa: E501

        collection_formats = {}

        path_params = {}

        query_params = []

        header_params = {}

        form_params = []
        local_var_files = {}

        body_params = None
        if "create_route_request" in local_var_params:
            body_params = local_var_params["create_route_request"]
        # HTTP header `Accept`
        header_params["Accept"] = self.api_client.select_header_accept(
            ["application/json"]
        )  # noqa: E501

        # HTTP header `Content-Type`
        header_params[
            "Content-Type"
        ] = self.api_client.select_header_content_type(  # noqa: E501
            ["application/json"]
        )  # noqa: E501

        # Authentication setting
        auth_settings = ["basicAuth"]  # noqa: E501

        return self.api_client.call_api(
            "/routes",
            "POST",
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_type="RoutesListResponse",  # noqa: E501
            auth_settings=auth_settings,
            async_req=local_var_params.get("async_req"),
            _return_http_data_only=local_var_params.get(
                "_return_http_data_only"
            ),  # noqa: E501
            _preload_content=local_var_params.get("_preload_content", True),
            _request_timeout=local_var_params.get("_request_timeout"),
            collection_formats=collection_formats,
        )

    def post_create_route_if_not_exists(
        self, route_request, comparison_keys=RouteConstants.RouteComparisonKeys
    ):
        """Create route if it doesn not exist for client. Compare based on keys.

        Arguments:
            client {VNS3Client}
            route {dict} - models.Route dictionary

        Keyword Arguments:
            comparison_keys {List[str]} - list of models.Route attributes to compare when checking for existence.
                                          default: ["cidr", "interface", "gateway"]

        Returns:
            [models.RoutesListResponse] -  dictionary of routes keyed by route Ids (ints). id -> models.Route
        """

        def __to_route_tuple(route, keys):
            return tuple(route[key] for key in keys)

        routes_response = self.api_client.routing.get_routes().response
        route_tuples = {
            __to_route_tuple(
                current_route.to_dict(), comparison_keys
            ): current_route.to_dict()
            for current_route in routes_response.values()
        }
        new_route_tuple = __to_route_tuple(route_request, comparison_keys)
        if new_route_tuple in route_tuples:
            Logger.debug(
                "Route already exists. Skipping creation.",
                host=self.api_client.host_uri,
            )
            return routes_response

        return self.api_client.routing.post_create_route(route_request).response
