# coding: utf-8

"""
    Python SDK for Opsgenie REST API

    Python SDK for Opsgenie REST API  # noqa: E501

    The version of the OpenAPI document: 2.0.0
    Contact: support@opsgenie.com
    Generated by: https://openapi-generator.tech
"""


import pprint
import re  # noqa: F401

import six

import time
import json
import certifi
import urllib3

import opsgenie_sdk
from opsgenie_sdk.models.success_data import SuccessData  # noqa: F401,E501
from opsgenie_sdk.rest import ApiException


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

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'request_id': 'str',
        'took': 'float',
        'result': 'str',
        'data': 'SuccessData'
    }
    openapi_types['url'] = 'str'

    attribute_map = {
        'request_id': 'requestId',
        'took': 'took',
        'result': 'result',
        'data': 'data'
    }
    attribute_map['url'] = 'url'

    def __init__(self, request_id=None, took=0.0, result=None, data=None, url=None):  # noqa: E501
        """SuccessResponse - a model defined in OpenAPI"""  # noqa: E501

        self._request_id = None
        self._took = None
        self._result = None
        self._data = None
        self.discriminator = None

        self.request_id = request_id
        self.took = took
        if result is not None:
            self.result = result
        if data is not None:
            self.data = data

        if url is not None:
            self.url = url
        else:
            self.url = None

        self._id = None
        self.conf = opsgenie_sdk.configuration.Configuration()
        self.logger = self.conf.logger["package_logger"]
    @property
    def request_id(self):
        """Gets the request_id of this SuccessResponse.  # noqa: E501


        :return: The request_id of this SuccessResponse.  # noqa: E501
        :rtype: str
        """
        return self._request_id

    @request_id.setter
    def request_id(self, request_id):
        """Sets the request_id of this SuccessResponse.


        :param request_id: The request_id of this SuccessResponse.  # noqa: E501
        :type: str
        """
        if request_id is None:
            raise ValueError("Invalid value for `request_id`, must not be `None`")  # noqa: E501

        self._request_id = request_id

    @property
    def took(self):
        """Gets the took of this SuccessResponse.  # noqa: E501


        :return: The took of this SuccessResponse.  # noqa: E501
        :rtype: float
        """
        return self._took

    @took.setter
    def took(self, took):
        """Sets the took of this SuccessResponse.


        :param took: The took of this SuccessResponse.  # noqa: E501
        :type: float
        """
        if took is None:
            raise ValueError("Invalid value for `took`, must not be `None`")  # noqa: E501

        self._took = took

    @property
    def result(self):
        """Gets the result of this SuccessResponse.  # noqa: E501


        :return: The result of this SuccessResponse.  # noqa: E501
        :rtype: str
        """
        return self._result

    @result.setter
    def result(self, result):
        """Sets the result of this SuccessResponse.


        :param result: The result of this SuccessResponse.  # noqa: E501
        :type: str
        """

        self._result = result

    @property
    def data(self):
        """Gets the data of this SuccessResponse.  # noqa: E501


        :return: The data of this SuccessResponse.  # noqa: E501
        :rtype: SuccessData
        """
        return self._data

    @data.setter
    def data(self, data):
        """Sets the data of this SuccessResponse.


        :param data: The data of this SuccessResponse.  # noqa: E501
        :type: SuccessData
        """

        self._data = data

    @property
    def url(self):
        """Gets the url of this SuccessResponse.  # noqa: E501


        :return: The url of this SuccessResponse.  # noqa: E501
        :rtype: str
        """
        return self._url

    @url.setter
    def url(self, url):
        """Sets the url of this SuccessResponse.


        :param url: The url of this SuccessResponse.  # noqa: E501
        :type: str
        """

        self._url = url

    def retrieve_result(self):
        conf = self.conf
        api_key = conf.api_key_prefix.get('Authorization') + ' ' + conf.api_key.get('Authorization')
        http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
        headers = {
            'Authorization': api_key
        }

        request_url = self._build_request_url_(conf.host)

        attempt_count = 0
        MAX_NUMBER_OF_RETRIES = conf.short_polling_max_retries
        condition = True
        response = None

        while condition:
            if attempt_count > 0:
                time.sleep(2 * attempt_count * 0.2)

            try:
                self.logger.debug(
                    str(attempt_count + 1) + ' attempt to retrieve result with request_id: ' + str(self.request_id))
                response = http.request(method='GET', url=request_url, headers=headers)
            except ApiException as err:
                print("Exception when calling success_response->retrieve_result: %s\n" % err)

            response_headers = response.headers
            if response_headers is not None:
                rate_limit_state = response_headers.get('X-RateLimit-State')
                status_code = response.status

                if rate_limit_state == 'THROTTLED':
                    should_retry = True
                    self.logger.debug('Should retry because X-RateLimit-State is THROTTLED')
                elif status_code == 429:
                    should_retry = True
                    self.logger.debug('Should retry because Status is 429')
                elif 500 <= status_code <= 599:
                    should_retry = True
                    self.logger.debug('Should retry because Status is ' + status_code)
                else:
                    should_retry = False
                    response_body = response.data
                    response_body_decoded = json.loads(response_body)
                    response_body_decoded_data = response_body_decoded.get('data')
                    if response_body_decoded_data is not None:
                        self._id = response_body_decoded_data.get('alertId')
                        if self._id is None:
                            self._id = response_body_decoded_data.get('incidentId')

                attempt_count += 1

                if should_retry and attempt_count < MAX_NUMBER_OF_RETRIES:
                    condition = True
                else:
                    condition = False
            else:
                condition = True

        return response

    def retrieve_resulting_action(self):
        conf = self.conf
        api_key = conf.api_key_prefix.get('Authorization') + ' ' + conf.api_key.get('Authorization')
        http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
        headers = {
            'Authorization': api_key
        }

        if self._id is None:
            self.retrieve_result()

        request_url = self._build_request_url_(conf.host)

        try:
            response = http.request(method='GET', url=request_url, headers=headers)

            return response
        except ApiException as err:
            print("Exception when calling success_response->retrieve_result: %s\n" % err)

    def _build_request_url_(self, host):
        if 'alerts' in self.url:
            return host + '/v2/alerts/requests/' + self.request_id
        elif 'incident' in self.url:
            return host + '/v1/incidents/requests/' + self.request_id
        else:
            raise ApiException(reason='Short polling is not currently supported for this domain')

    @property
    def id(self):
        return self._id

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            if attr != 'url':
                value = getattr(self, attr)
                if isinstance(value, list):
                    result[attr] = list(map(
                        lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                        value
                    ))
                elif hasattr(value, "to_dict"):
                    result[attr] = value.to_dict()
                elif isinstance(value, dict):
                    result[attr] = dict(map(
                        lambda item: (item[0], item[1].to_dict())
                        if hasattr(item[1], "to_dict") else item,
                        value.items()
                    ))
                else:
                    result[attr] = value
        if issubclass(SuccessResponse, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, SuccessResponse):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other
