from __future__ import unicode_literals

import os
import threading
import warnings
from wsgiref.simple_server import make_server, WSGIRequestHandler

import requests

warnings.filterwarnings(action='ignore', category=DeprecationWarning,
                        module='requests')


TEST_FILE_PATH = os.path.join(os.path.dirname(__file__), 'test_files')


class SilentWSGIHandler(WSGIRequestHandler):
    def log_message(*args):
        pass


class TestServer(object):
    """
    Wraps a WSGI application and allows you to make real HTTP
    requests against it
    """

    def __init__(self, application):
        self.application = application
        self.server = make_server('127.0.0.1', 0, application,
                                  handler_class=SilentWSGIHandler)

    def get(self, *args, **kwargs):
        return self.request('get', *args, **kwargs)

    def request(self, method, path, *args, **kwargs):
        url = 'http://{0[0]}:{0[1]}{1}'.format(self.server.server_address, path)
        thread = threading.Thread(target=self.server.handle_request)
        thread.start()
        response = requests.request(method, url, *args, **kwargs)
        thread.join()
        return response


class Files(object):
    def __init__(self, directory, **files):
        self.directory = os.path.join(TEST_FILE_PATH, directory)
        for name, path in files.items():
            url = '/' + path
            with open(os.path.join(self.directory, path), 'rb') as f:
                content = f.read()
            setattr(self, name + '_path', path)
            setattr(self, name + '_url', url)
            setattr(self, name + '_content', content)
