# -*- coding: utf-8 -*-
import os
import sys

from requests.exceptions import ConnectionError
from requests.models import Request, Response

from .exceptions import SlownessException

IS_TRAVIS = 'TRAVIS' in os.environ
SKIP_SLOWNESS = "JURISCRAPER_SKIP_SLOWNESS_ERRORS" in os.environ or IS_TRAVIS


class MockRequest(Request):
    def __init__(self, url=None):
        super(Request, self).__init__()
        self.url = url
        #: Resulting :class:`HTTPError` of request, if one occurred.
        self.error = None

        #: Encoding to decode with when accessing r.content.
        self.encoding = None

        #: The :class:`Request <Request>` that created the Response.
        self.request = self

    def get(self):
        r = Response()
        try:
            with open(self.url, mode='rb') as stream:
                r._content = stream.read()
                #: Integer Code of responded HTTP Status.
                r.status_code = 200
                if self.url.endswith('json'):
                    r.headers['content-type'] = 'application/json'
        except IOError as e:
            r.status_code = 404
            raise ConnectionError(e)

        r._content_consumed = True

        #: Final URL location of Response.
        r.url = self.url

        # Return the response.
        return r


def warn_or_crash_slow_parser(duration, warn_duration=1, max_duration=15):
    msg = ''
    if duration > max_duration:
        if sys.gettrace() is None and not SKIP_SLOWNESS:
            # Only do this if we're not debugging. Debuggers make things slower
            # and breakpoints make things stop.
            raise SlownessException(
                "This scraper took {duration}s to test, which is more than the "
                "allowed speed of {max_duration}s. Please speed it up for "
                "tests to pass.".format(duration=duration,
                                        max_duration=max_duration)
            )
    elif duration > warn_duration:
        msg = ' - WARNING: SLOW SCRAPER'
    else:
        msg = ''
    return msg

@@ -37,16 +37,32 @@
 port sys
+%0Aimport warnings
 %0A%0Afrom r
@@ -193,24 +193,32 @@
 eption%0A%0A
-IS_TRAVI
+WARN_SLOW_SRAPER
 S = 'TRA
@@ -240,85 +240,243 @@
 ron%0A
-SKIP_SLOWNESS = %22JURISCRAPER_SKIP_SLOWNESS_ERRORS%22 in os.environ or IS_TRAVIS
+# FIXME: when testing, should we only find the first warning%0A# or provide a warning for each slow scraper?%0Awarnings.simplefilter(%22always%22)%0A%0A%0Aclass SlownessWarning(UserWarning):%0A    pass%0A%0A%0Aclass TooSlowWarning(SlownessWarning):%0A    pass
 %0A%0A%0Ac
@@ -1663,20 +1663,24 @@
 not 
-SKIP
+WARN
 _SLOW
-NES
+_SRAPER
 S:%0A 
@@ -1918,20 +1918,16 @@
 re than 
-the 
 %22%0A      
@@ -1937,16 +1937,20 @@
        %22
+the 
 allowed 
@@ -2140,16 +2140,207 @@
       )%0A
+        elif WARN_SLOW_SRAPERS:%0A            msg = ' - WARNING: SLOW SCRAPER'%0A            wmsg = %22WARNING: VERY SLOW SCRAPER (potential Error)%22%0A            warnings.warn(wmsg, TooSlowWarning)%0A
     elif
@@ -2403,24 +2403,88 @@
 OW SCRAPER'%0A
+        warnings.warn('WARNING: SLOW SCRAPER', SlownessWarning)%0A
     else:%0A  

rework slowness warnings