#encoding:UTF-8

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

from django.conf import settings
from django.contrib.auth.models import *
from django.test import TestCase
from ldt.core.models import Owner
from ldt.test.testcases import OAuthWebTestCase, OAuthTestCase, WebTestCase 
from ldt.text import VERSION_STR
from ldt.text.models import *
from ldt.text.views import *
from oauth_provider.models import Resource, Consumer, Token, Nonce
import datetime
import logging
import lxml.etree
import time
import unittest
import urllib
import uuid

CONSUMER_KEY = 'dpf43f3p2l4k3l03'
CONSUMER_SECRET = 'kd94hf93k423kf44'


class OnServerGlobalTest(OAuthWebTestCase):
    
    fixtures = ['oauth_data','base_data']
    
    def setUp(self):
        
        self.id = "mypersonnalid"
        self.title = "titre de l\'annotation"
        self.text = "texte selectionne lors de la creation de l\'annotation"
        self.textupdate = "texte selectionne a nouveau lors de la creation de l\'annotation"
        self.descupdate = "texte de description update"
        self.contributor = "oaubert"
        self.creator = "wakimd"
        self.uri = "http://www.leezam.com/pub/epub/123456!/OPS/chapter2.xhtml#pos=56,168"
        self.content1 = '<iri><text-annotation><id>'+self.id+'</id><uri>'+self.uri+'</uri><tags><tag>tag1</tag><tag>tag2</tag></tags><content><color>#AAAAAA</color><description><![CDATA[texte de description]]></description><title>'+self.title+'</title><text>'+self.text+'</text></content><meta><contributor>oaubert</contributor><contributor-id>79cd0532-1dda-4130-b351-6a181130a7c9</contributor-id><created>2010-09-06 12:33:53.417550</created><creator>'+self.creator+'</creator><creator-id>79cd0532-1dda-4130-b351-6a181130a7c9</creator-id><modified>2010-09-06 12:33:53.420459</modified></meta></text-annotation></iri>'        
        self.contentupdate = '<iri><text-annotation><id></id><uri></uri><tags><tag>tag1</tag><tag>tag2new</tag><tag>tag3</tag></tags><content><color>#DDDDDD</color><description>'+self.descupdate+'</description><title></title><text>'+self.textupdate+'</text></content><meta><contributor>'+self.contributor+'</contributor><contributor-id>80cd0532-1dda-4130-b351-6a181130a7c9</contributor-id><created></created><creator></creator><creator-id></creator-id><modified>2010-11-06 12:33:53.420459</modified></meta></text-annotation></iri>'
        
        self.set_login_url("/auth_accounts/login/")
        self.set_consumer(CONSUMER_KEY, CONSUMER_SECRET)


    def test_everything(self):

        self.assertTrue(self.client.login(username='jane', password='toto'))
        
        #test POST
        creation = self.client.post("/api/"+VERSION_STR+"/text/create/", data={'content': self.content1})            
        self.assertEqual(creation.status_code,200)
        annot = Annotation.objects.get(external_id=self.id)
        self.assertEqual(str(annot.creation_date)[:11], str(datetime.datetime.now())[:11])
        self.assertEqual(annot.text,self.text)
        self.assertEqual(len(annot.tags.split(",")),2)
        
        #test GET
        get = self.client.get("/api/"+VERSION_STR+"/text/get/"+self.id+"")
        self.assertEqual(get.status_code,200)
        annot = lxml.etree.fromstring(get.content)
        self.assertTrue('tag1','tag2' in annot.xpath("/iri/text-annotation/tags/tag/text()"))
        self.assertEqual(annot.xpath("/iri/text-annotation/content/title/text()")[0],self.title)
        
        #test OPTIONS
        options = self.client.options("/api/"+VERSION_STR+"/text/get/"+self.id+"")
        self.assertEqual(options.status_code,200)
        self.assertEqual(options.content, get.content)
       
        #test HEAD
        head = self.client.head("/api/"+VERSION_STR+"/text/get/"+self.id+"")
        self.assertEqual(head.status_code,200)
        self.assertEqual(head['content-type'],'text/xml;charset=utf-8')
        self.assertEqual(head['content-language'],'fr-fr')
        self.assertEqual(head.content,'')
               
        #test LOGOUT
        self.client.logout()
        
        creation = self.client.post("/api/"+VERSION_STR+"/text/create/", data={'content': self.content1})            
        self.assertEqual(creation.status_code,401)
        
        self.assertTrue(self.client.login(username='jane', password='toto'))

        # filter
        filt1 = self.client.get("/api/"+VERSION_STR+"/text/filter/", data={"uri":self.uri})
        self.assertEqual(filt1.status_code,200)
        doc = lxml.etree.fromstring(filt1.content)
        self.assertEqual(len(doc.xpath("/iri/text-annotation")),2)
        for elem in doc.xpath("/iri/text-annotation/uri/text()"):
            self.assertEqual(elem,self.uri)

        filt2 = self.client.get("/api/"+VERSION_STR+"/text/filter/", data={"creator":self.contributor})
        self.assertEqual(filt2.status_code,200)
        self.assertEqual(filt2.content, '<iri/>\n')

        #test PUT
        update = self.client.put("/api/"+VERSION_STR+"/text/update/"+self.id+"", data={'content':self.contentupdate})
        self.assertEqual(update.status_code,200)
        annot = Annotation.objects.get(external_id=self.id)
        self.assertEqual(str(annot.creation_date)[:11],str(datetime.datetime.now())[:11])
        self.assertEqual(annot.external_id,self.id)
        self.assertTrue('tag1','tag2' not in annot.tags)
        self.assertTrue('mytag','tag2new' in annot.tags)
        self.assertEqual(annot.description,self.descupdate)
        self.assertEqual(annot.text,self.textupdate)
        self.assertEqual(annot.contributor,self.contributor)
        
        #test DELETE
        delete = self.client.delete("/api/"+VERSION_STR+"/text/delete/"+self.id+"")
        self.assertEqual(delete.content, "")
        self.assertEqual(delete.status_code,200)   
        self.assertRaises(Annotation.DoesNotExist, Annotation.objects.get, external_id=self.id)  

        self.client.logout()


    def test_errors(self):
        
        self.assertTrue(self.client.login(username='jane', password='toto'))
        
        creation = self.client.post("/api/"+VERSION_STR+"/text/create/", data={'content': self.content1})            
        self.assertEqual(creation.status_code,200)
        
        creation = self.client.post("/api/"+VERSION_STR+"/text/create/", data={'content': self.content1})            
        self.assertEqual(creation.status_code,409)
        
        get = self.client.get("/api/"+VERSION_STR+"/text/get/1")
        self.assertEqual(get.status_code,404)
        
        update = self.client.put('/api/'+ VERSION_STR +'/text/update/1', {'content':self.contentupdate})
        self.assertEqual(update.status_code,404)
        
        delete = self.client.delete("/api/"+VERSION_STR+"/text/delete/1")
        self.assertEqual(delete.status_code,404)
        
        delete = self.client.delete("/api/"+VERSION_STR+"/text/delete/"+self.id+"")
        self.assertEqual(delete.status_code,200)
        self.assertEqual(delete.content, "")
        
        self.client.logout()


class WebClientTest(WebTestCase):
    
    fixtures = ['oauth_data', 'base_data']
    
    def setUp(self):
        self.set_login_url("/auth_accounts/login/")
    
    def test_get(self):
        self.assertTrue(self.client.login(username='jane', password='toto'))
        
        get = self.client.get("/api/"+VERSION_STR+"/text/get/z2c1d1fa-629d-4520-a3d2-955b4f2582c0")
        self.assertEqual(get.status_code,200)
        annot = lxml.etree.fromstring(get.content)
        self.assertTrue('tag1','tag2' in annot.xpath("/iri/text-annotation/tags/tag/text()"))
        
        