import unittest
import re
import pickle
import os
import io
import gzip
import zlib
import urllib
from base64 import b64encode

import responses
from responses import matchers
from contextlib import contextmanager


CONSUMER_KEY = os.getenv("CONSUMER_KEY")
CONSUMER_SECRET = os.getenv("CONSUMER_SECRET")

# different modes
# INTEGRATION_TESTING -> Targets real OPE endpoints + record all calls
INTEGRATION_TESTING = os.getenv("INTEGRATION_TESTING")
if INTEGRATION_TESTING and not (CONSUMER_KEY and CONSUMER_SECRET):
    raise RuntimeError("Integration testing requires credentials!")

http_methods = ["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH"]


class ReplayResponse(responses.Response):
    def __init__(self, request, response):
        self._request = request
        self._response = response
        parsed_url = urllib.parse.urlparse(request.url)
        super().__init__(
            request.method,
            request.url,
            body=response.content,
            status=response.status_code,
            headers=response.headers,
            match=[matchers.query_string_matcher(parsed_url.query)],
        )
        if "gzip" in response.headers.get("Content-Encoding", ""):
            self.body = self._gzip_compress(self.body)

    @staticmethod
    def _gzip_compress(data):
        if hasattr(data, "read"):
            data = data.read()
        if isinstance(data, str):
            data = data.encode()
        # window size flag, +25 to +31 include a basic gzip
        # header and trailing checksum
        wbits = 28
        compressor = zlib.compressobj(wbits=wbits)
        compressed_chunks = [compressor.compress(data), compressor.flush()]
        return b"".join(compressed_chunks)


class ReplayResponsesTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        if INTEGRATION_TESTING:
            cls.prepare_integration_test()
        cls.recordpath = "{0}/data/{1}.{2}.pickle.gz".format(
            os.path.dirname(__file__), cls.__module__.split(".")[-1], cls.__name__
        )
        cls.requests_mock = responses.RequestsMock()
        if INTEGRATION_TESTING:
            cls._records = {}
        else:
            with gzip.open(cls.recordpath) as file:
                cls._records = pickle.load(file)

    def setUp(self):
        if INTEGRATION_TESTING:
            url = re.compile(".*")
            for method in http_methods:
                self.requests_mock.add(responses.PassthroughResponse(method, url))
            self.requests_mock.assert_all_requests_are_fired = False
            self.requests_mock.response_callback = self._record_streaming_response_body
        else:
            calls = self._records.get(self.record_key, responses.CallList())
            for request, response in calls:
                replay = ReplayResponse(request, response)
                self.requests_mock.add(replay)
            self.requests_mock.assert_all_requests_are_fired = True
        self.addCleanup(self.requests_mock.reset)
        self.requests_mock.start()
        self.addCleanup(self.requests_mock.stop)

    def tearDown(self):
        if INTEGRATION_TESTING:
            calls = list(self.requests_mock.calls)
            if calls:
                self._records[self.record_key] = calls

    @classmethod
    def tearDownClass(cls):
        if INTEGRATION_TESTING:
            with gzip.open(cls.recordpath, mode="wb") as file:
                pickle.dump(cls._records, file)

    @property
    def record_key(self):
        return self._testMethodName

    @staticmethod
    def _record_streaming_response_body(response):
        if not response.raw.closed:
            content = response.content
            response.raw = io.BytesIO(content)
        return response

    @classmethod
    def prepare_integration_test(cls):
        """This method can be used to check preconditions for integration tests"""
        pass


class DataServiceTestCase(ReplayResponsesTestCase):
    credentials = (
        CONSUMER_KEY or "pewh0CiBQ5Gl8BX7K2i8vww9tsr0",
        CONSUMER_SECRET or "cP58wJbenKRPaK9RKA8ODPxHmkw1",
    )

    @classmethod
    def tearDownClass(cls):
        if INTEGRATION_TESTING:
            key, secret = map(str.encode, cls.credentials)
            sensitive = b64encode(key + b":" + secret)
            xs = len(key) * b"x"
            crossed = b64encode(xs + b":" + xs)
            pickled = pickle.dumps(cls._records)
            sanitized = pickled.replace(sensitive, crossed)
            with gzip.open(cls.recordpath, mode="wb") as file:
                file.write(sanitized)


class FakeProduct:
    def __init__(self, id=None, collection=None):
        self._id = id or "product"
        self.collection = collection or FakeCollection()

    @property
    def md5(self):
        return None


class FakeCollection:
    def __init__(self, id=None):
        self._id = id or "collection"


class FakeCustomisation:
    def __init__(self, states_to_return, cid=None):
        self.states_to_return = iter(states_to_return)
        self.logfile = f"Fake Log: {states_to_return}"
        self._id = cid or "test"
        self.deleted = False

    @property
    def status(self):
        return next(self.states_to_return)

    @property
    def outputs(self):
        return ["prod1.nc", "prod2.nc"]

    def kill(self):
        pass

    def delete(self):
        if not self.deleted:
            self.deleted = True
        else:
            from eumdac.errors import CustomisationError

            raise CustomisationError("double deletion")

    @contextmanager
    def stream_output_iter_content(self, output, chunks=0):
        yield [bytes("test", "utf-8")]


class FakeTailor:
    def __init__(self):
        self.user_info = {
            "username": "test",
        }
        self.quota = {
            "data": {
                "test": {
                    "space_usage_percentage": 95,
                }
            }
        }

    def get_customisation(self, id):
        return FakeCustomisation(["QUEUED", "RUNNING", "DONE"], cid=id)

    def new_customisation(self, product, chain):
        return FakeCustomisation(["QUEUED", "RUNNING", "DONE"], cid=None)


class FakeStore:
    def get_product(self, col_id, p_id):
        return FakeProduct(id=p_id, collection=FakeCollection(id=col_id))
