import threading
import sys
from django.contrib.sessions.models import Session
from django.template import RequestContext, TemplateDoesNotExist
from django.test import Client, TestCase
from mock import MagicMock, Mock, patch
from django_mobile import get_flavour, set_flavour
from django_mobile.conf import settings
from django_mobile.compat import get_engine
from django_mobile.middleware import MobileDetectionMiddleware, \
    SetFlavourMiddleware

IS_PYTHON_3 = sys.version > '3'

def _reset():
    '''
    Reset the thread local.
    '''
    import django_mobile
    del django_mobile._local
    django_mobile._local = threading.local()

def str_p3_response( string ) :
    """
    Since response.content is a binary string in python 3,
    we decode it to make it comparable to str objects
    ( python 2 compatibility )
    """
    if IS_PYTHON_3 :
        return string.decode( 'ASCII' )
    return string

class BaseTestCase(TestCase):
    def setUp(self):
        _reset()

    def tearDown(self):
        _reset()


class BasicFunctionTests(BaseTestCase):
    def test_set_flavour(self):
        set_flavour('full')
        self.assertEqual(get_flavour(), 'full')
        set_flavour('mobile')
        self.assertEqual(get_flavour(), 'mobile')
        self.assertRaises(ValueError, set_flavour, 'spam')

    def test_set_flavour_with_cookie_backend(self):
        original_FLAVOURS_STORAGE_BACKEND = settings.FLAVOURS_STORAGE_BACKEND
        try:
            settings.FLAVOURS_STORAGE_BACKEND = 'cookie'
            response = self.client.get('/')
            self.assertFalse(settings.FLAVOURS_COOKIE_KEY in response.cookies)
            response = self.client.get('/', {
                settings.FLAVOURS_GET_PARAMETER: 'mobile',
            })
            self.assertTrue(settings.FLAVOURS_COOKIE_KEY in response.cookies)
            self.assertTrue(response.cookies[settings.FLAVOURS_COOKIE_KEY], u'mobile')
            self.assertContains(response, 'Mobile!')