# 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 random

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, api_client=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

        self.url = url
        self.api_client = api_client

        self._id = None
        self.conf = api_client.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):
        domain_api_client = self._get_domain_api_client_()
        MAX_NUMBER_OF_RETRIES = self.conf.short_polling_max_retries
        condition = True
        response = None
        attempt_count = 0

        while condition:
            if attempt_count > 0:
                sleep_time = random.uniform(0, (0.2 * 2 ** attempt_count))
                time.sleep(sleep_time)

            try:
                response = domain_api_client.get_incident_request_status(request_id=self.request_id)
            except AttributeError:
                response = domain_api_client.get_request_status(request_id=self.request_id)

            if response.data.is_success is True:
                should_retry = False

                if hasattr(response.data, "alert_id"):
                    self._id = response.data.alert_id
                elif hasattr(response.data, "incident_id"):
                    self._id = response.data.incident_id
            else:
                should_retry = True

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

            attempt_count += 1

        return response

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

        domain_api_client = self._get_domain_api_client_()

        try:
            action = domain_api_client.get_alert(identifier=self._id)
        except AttributeError:
            action = domain_api_client.get_incident(identifier=self._id)

        return action

    def _get_domain_api_client_(self):
        if 'alerts' in self.url:
            return opsgenie_sdk.AlertApi(api_client=self.api_client)
        elif 'incident' in self.url:
            return opsgenie_sdk.IncidentApi(api_client=self.api_client)
        else:
            raise ApiException(reason='Short polling is not currently supported for this domain')

    @property
    def id(self):
        if self._id is None:
            self.retrieve_result()

        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
