#encoding:UTF-8

""" Run these tests with 'python manage.py test text'  """

from django.conf import settings, settings
from django.contrib.auth.models import *
from django.db import transaction
from django.test import TestCase
from django.test.client import Client
from ldt.test.testcases import OAuthTestCase
from ldt.text import VERSION_STR
from ldt.text.models import Annotation
from ldt.text.views import *
from oauth2 import Request, SignatureMethod_HMAC_SHA1, SignatureMethod_PLAINTEXT, \
    generate_nonce
from oauth_provider.consts import OUT_OF_BAND
from oauth_provider.models import Resource, Consumer, Token, Nonce
import logging
import time
import urlparse
        
class OAuthTestDelete(TestCase):
    def setUp(self):
        #create a user
        self.jane = User.objects.create_user('jane', 'jane@example.com', 'toto')

        resource = Resource(name='all', url='/api/'+VERSION_STR+'/text/delete/')
        resource.save()

        resource = Resource(name='delete', url='/api/'+VERSION_STR+'/text/delete/')
        resource.save()

        self.CONSUMER_KEY = 'dpf43f3p2l4k3l03'
        self.CONSUMER_SECRET = 'kd94hf93k423kf44'
        self.consumer = Consumer(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET, name='printer.example.com', user=self.jane)
        self.consumer.save()
        
        self.nonce = generate_nonce(8)
        
        #auth parameters
        self.parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_signature_method': 'PLAINTEXT',
            'oauth_signature': '%s&' % self.CONSUMER_SECRET,
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': self.nonce,
            'oauth_version': '1.0',
            'oauth_callback': OUT_OF_BAND,
            'scope':'delete'
        }
                
        self.annotation = Annotation(external_id="d2c1d1fa-629d-4520-a3d2-955b4f2582c0",title="titre de l\'annotation",text="texte selectionne lors de la creation de l\'annotation",color="#AAAAAA", creation_date="2010-09-06T12:33:53.417550", update_date="2010-09-06T12:33:53.420459")
        self.annotation.save()
        
        
    def test_auth_access_delete(self):
        ## REQUEST TOKEN
        
        response = self.client.get("/oauth/request_token/", self.parameters)
        #self.assertEqual(response.content,"  ")
        self.assertEqual(response.status_code,200)   
        token = list(Token.objects.all())[-1]
        logging.debug(response.content)
        data = urlparse.parse_qs(response.content)
        self.assertEqual(token.key, data["oauth_token"][0])
        self.assertEqual(token.secret, data['oauth_token_secret'][0])
        self.assertTrue(data['oauth_callback_confirmed'][0])
        self.assertEqual(token.callback, None),

#        token.callback = OUT_OF_BAND
#        token.save()
#        
        ## USER AUTHORIZATION
        
        parameters = {
            'oauth_token': token.key,
        }
        
        response = self.client.get("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code,302)
        self.assertTrue(token.key in response['Location'])
        logging.debug(repr(response['location']))
        
        self.client.login(username='jane', password='toto')
        
        response = self.client.get("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code,200)
        self.assertEqual(response.content,'Fake authorize view for printer.example.com.')
    
#        parameters['authorize_access'] = 0
#        response = self.c.post("/oauth/authorize/", parameters)
#        self.assertEqual(response.content, "Fake callback view.")
        
        # fake authorization by the user
        parameters['authorize_access'] = 1
        response = self.client.post("/oauth/authorize/", parameters)
        self.assertEqual(response.status_code,200)
        token = list(Token.objects.all())[-1]
        #self.assertTrue(token.key in response['Location'])
        self.assertTrue(token.is_approved)
        
        ## ACCESS TOKEN
        
        parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_token': token.key,
            'oauth_signature_method': 'PLAINTEXT',
            'oauth_signature': '%s&%s' % (self.CONSUMER_SECRET, token.secret),
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': self.nonce,
            'oauth_version': '1.0',
            'oauth_verifier': token.verifier,
        }
        response = self.client.get("/oauth/access_token/", parameters)
        
        access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1]
        self.assertTrue(access_token.key in response.content)
        self.assertTrue(access_token.secret in response.content)
        self.assertEqual(access_token.user.username, u'jane')
        
        ## ACCESSING PROTECTED VIEW
        
        parameters = {
            'oauth_consumer_key': self.CONSUMER_KEY,
            'oauth_token': access_token.key,
            'oauth_signature_method': 'HMAC-SHA1',
            'oauth_timestamp': str(int(time.time())),
            'oauth_nonce': self.nonce,
            'oauth_version': '1.0',
            'id':'d2c1d1fa-629d-4520-a3d2-955b4f2582c0'
        }
        
        oauth_request = Request.from_token_and_callback(access_token, http_url='http://testserver/api/'+VERSION_STR+'/text/delete/', parameters=parameters, http_method="POST")
        signature_method = SignatureMethod_HMAC_SHA1()
        signature = signature_method.sign(oauth_request, self.consumer, access_token)

        parameters['oauth_signature'] = signature
        #self.assertEqual(signature, "  ")
        response = self.client.post("/api/"+VERSION_STR+"/text/delete/", parameters)
        self.assertEqual(response.content, "")
        self.assertEqual(response.status_code,200)
        
        self.client.logout()
        access_token.delete()


class OAuthTestDeleteClient(OAuthTestCase):
    def setUp(self):
        #create a user
        self.jane = User.objects.create_user('jane', 'jane@example.com', 'toto')

        resource = Resource(name='all', url='/api/'+VERSION_STR+'/text/delete/')
        resource.save()

        resource = Resource(name='delete', url='/api/'+VERSION_STR+'/text/delete/')
        resource.save()

        self.CONSUMER_KEY = 'dpf43f3p2l4k3l03'
        self.CONSUMER_SECRET = 'kd94hf93k423kf44'
        
        self.set_consumer(self.CONSUMER_KEY, self.CONSUMER_SECRET)
        
        self.consumer = Consumer(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET, name='printer.example.com', user=self.jane)
        self.consumer.save()
                        
        self.annotation = Annotation(external_id="d2c1d1fa-629d-4520-a3d2-955b4f2582c0",title="titre de l\'annotation",text="texte selectionne lors de la creation de l\'annotation",color="#AAAAAA", creation_date="2010-09-06T12:33:53.417550", update_date="2010-09-06T12:33:53.420459")
        self.annotation.save()
        
        
    def test_auth_access_delete(self):
        
        res = self.client.login(username='jane', password='toto')
        self.assertTrue(res)

        parameters = { 'id' : 'd2c1d1fa-629d-4520-a3d2-955b4f2582c0' }
        response = self.client.post(path="/api/"+VERSION_STR+"/text/delete/", data=parameters)
        self.assertEqual(response.content, "")
        self.assertEqual(response.status_code,200)
