# -*- coding: utf-8 -*-
# django_th classes
from django_th.services.services import ServicesMgr
from django_th.models import UserService
from django_th.models import ServicesActivated

# django classes
from django.conf import settings
from django.core.urlresolvers import reverse
from django.utils.log import getLogger

# pocket API
import pocket
from pocket import Pocket


logger = getLogger('django_th.trigger_happy')


"""
    handle process with pocket
    put the following in settings.py

    TH_POCKET = {
        'consummer_key': 'abcdefghijklmnopqrstuvwxyz',
    }

"""


class ServicePocket(ServicesMgr):

    def save_data(self, token, trigger_id, **data):
        """
            let's save the data
        """
        from th_pocket.models import Pocket

        if token and len(data['link']) > 0 and len(data['title']):
            # get the pocket data of this trigger
            trigger = Pocket.objects.get(trigger_id=trigger_id)

            pocket_instance = pocket.Pocket(
                settings.TH_POCKET['consummer_key'], token)

            item_id = pocket_instance.add(
                url=data['link'], title=data['title'], tags=(trigger.tag.lower()))

            sentance = str('pocket {} created').format(data['link'])
            logger.debug(sentance)

        else:
            logger.critical(
                "no token provided for trigger ID %s and title %s", trigger_id, data['title'])

    def auth(self, request):
        """
            let's auth the user to the Service
        """
        callbackUrl = 'http://%s%s' % (
            request.get_host(), reverse('pocket_callback'))

        request_token = Pocket.get_request_token(
            consumer_key=settings.TH_POCKET['consummer_key'], redirect_uri=callbackUrl)

        # Save the request token information for later
        request.session['request_token'] = request_token

        # URL to redirect user to, to authorize your app
        auth_url = Pocket.get_auth_url(
            code=request_token, redirect_uri=callbackUrl)

        return auth_url

    def callback(self, request):
        """
            Called from the Service when the user accept to activate it
        """

        try:
            # finally we save the user auth token
            # As we already stored the object ServicesActivated
            # from the UserServiceCreateView now we update the same
            # object to the database so :
            # 1) we get the previous objet
            us = UserService.objects.get(
                user=request.user,
                name=ServicesActivated.objects.get(name='ServicePocket'))
            # 2) then get the token
            access_token = Pocket.get_access_token(
                consumer_key=settings.TH_POCKET['consummer_key'],
                code=request.session['request_token'])

            us.token = access_token
            # 3) and save everything
            us.save()
        except KeyError:
            return '/'

        return 'pocket/callback.html'

@@ -367,16 +367,44 @@
 Pocket%0A%0A
+import datetime%0Aimport time%0A
 %0Alogger 
@@ -638,16 +638,1181 @@
 sMgr):%0A%0A
+    def process_data(self, **kwargs):%0A        %22%22%22%0A            get the data from the service%0A        %22%22%22%0A        data = %7B%7D%0A        trigger_id = 0%0A        if 'trigger_id' in kwargs:%0A            trigger_id = kwargs%5B'trigger_id'%5D%0A%0A        date_triggered = ''%0A        if 'date_triggered' in kwargs:%0A            date_triggered = kwargs%5B'date_triggered'%5D%0A        else:%0A            logger.critical(%0A                %22no date triggered provided for trigger ID %25s %22, trigger_id)%0A%0A        token = ''%0A        if 'token' in kwargs:%0A            token = kwargs%5B'token'%5D%0A        else:%0A            logger.critical(%0A                %22no token provided for trigger ID %25s %22, trigger_id)%0A%0A        if token and date_triggered:%0A            # get the timestamp version of the date time data%0A            #%C2%A0in data_triggered%0A            date_triggered = time.mktime(%0A                datetime.datetime.timetuple(date_triggered))%0A%0A            pocket_instance = pocket.Pocket(%0A                settings.TH_POCKET%5B'consummer_key'%5D, token)%0A            # get the data from the last time the trigger have been started%0A            data = pocket_instance.get(since=date_triggered)%0A%0A        return data%0A%0A
     def 
@@ -2002,31 +2002,8 @@
  %3E 0
- and len(data%5B'title'%5D)
 :%0A  
@@ -2221,16 +2221,93 @@
 token)%0A%0A
+            title = ''%0A            title = data%5B'title'%5D if 'title' in data%0A%0A
         
@@ -2381,29 +2381,21 @@
 , title=
-data%5B'
 title
-'%5D
 , tags=(
@@ -2622,21 +2622,20 @@
  %25s and 
-title
+link
  %25s%22, tr
@@ -2650,21 +2650,20 @@
 , data%5B'
-title
+link
 '%5D)%0A%0A   

add process_data