# coding: utf-8

"""
Worst of crutches and bicycles in this part of arcadia
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import time
import argparse

from requests.exceptions import ConnectionError


class NumberOrDiff(object):
    def __init__(self, s):
        if s.startswith('+'):
            self._sign = '+'
        elif s.startswith('-'):
            self._sign = '-'
        else:
            self._sign = '='
            s = s.lstrip('=')
        self._value = int(s, 10)

    @property
    def sign(self):
        return self._sign

    @property
    def value(self):
        return self._value

    def __repr__(self):
        return '{}{}'.format(self._sign, self._value)

    def __radd__(self, other):
        if isinstance(other, int):
            if self._sign != '=':
                result = other + self._value
                if result < 0:
                    raise RuntimeError('Negative result of applying diff {} to number {}'.format(self.__repr__(), other))
                else:
                    return result
            else:
                return self._value


def number_or_diff(string):
    try:
        return NumberOrDiff(string)
    except ValueError:
        raise argparse.ArgumentTypeError('Only base 10 integers with optional sign allowed')


def wait_minute():
    time.sleep(60)


def retry_if_connection_error(exception):
    return isinstance(exception, ConnectionError)
