
import os
import errno
import cProfile
import datetime
import random


log_dir = os.path.join(os.path.dirname(__file__), '..', 'profile_log')
try:
    os.mkdir(log_dir)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise


class Profile(object):

    def __init__(self, name=None):
        if name is None:
            name = '{}{}'.format(
                datetime.datetime.now().strftime('%Y-%m-%dT%H_%M_%S'),
                random.randrange(1000000),
            )
        self._name = name
        self._filename = os.path.join(log_dir, name)
        self._profile = cProfile.Profile(self._filename)

    def start(self):
        self._profile.start()

    def stop(self):
        self._profile.stop()
        self._profile.close()

    def __enter__(self):
        self.start()

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop()

    @property
    def profile(self):
        return self._profile


class ProfileMiddleware(object):

    def process_request(self, request):
        request._tux_profile = Profile()
        request._tux_profile.start()

    def process_response(self, request, response):
        request._tux_profile.stop()

