import pocket
import config
import time
import pymongo
import requests
import json
import unidecode

# initialize the connection to Mongo
client = pymongo.MongoClient()
db = client.nachios
timedb = db.time


def updateTimeDb():
    timedb.drop()
    timedb.insert_one(dict(
        _id="lastTime",
        lastTime=time.time()
    ))
    print "time updated."


def makeStep(titleString):
    url = 'https://nachapp.com/api/users/' + str(config.nachUser) + '/nodes'
    newStep = requests.post(url,
                            auth=(config.nachApiKey, ''),
                            verify=False,
                            data={
                                  "parent": config.nachPTRNode,
                                  "type": "Step",
                                  "name": titleString
                            })
    # pause - completion doesn't work if we do not do this
    response = json.loads(newStep.text)
    nodeId = response['id']
    time.sleep(8)
    url = 'https://nachapp.com/api/todos/' + str(nodeId)
    newCompletion = requests.patch(url,
                                   auth=(config.nachApiKey, ''),
                                   verify=False,
                                   data={"status": "completed"})

# when did we last check for new articles?
lastTime = timedb.find_one({"_id": "lastTime"})['lastTime']

# initialize pocket
p = pocket.Pocket(config.consumerKey, config.accessToken)

# get all archived articles modified since last check
articleList = p.get(detailType="simple", state="archive", since=lastTime)

# this goes through the raw Pocket data for each item and finds a nonblank
# string to use as a title. The IFTTT -> Hook version of this was failing
# I think because sometimes the only usable title is resolved_url and
# IFTTT sends a blank title in such cases.

# also IFTTT is really slow compared to running this on a 5 minute cron.
try:
    for each in articleList[0]['list'].itervalues():
        try:
            ert = each['resolved_title']
        except:
            print each
        for title in(
                each['resolved_title'],
                each['given_title'],
                each['resolved_url']):
            if len(title) == 0:
                pass
            else:
                makeStep(title)
                print "made step for {0}".format(unidecode.unidecode(title))
                break
except AttributeError:
    print "no articles found"

# set last checked time to now

updateTimeDb()

@@ -92,16 +92,29 @@
 nidecode
+%0Aimport arrow
 %0A%0A# init
@@ -231,16 +231,21 @@
 eTimeDb(
+rtime
 ):%0A    t
@@ -356,16 +356,21 @@
  print %22
+%7B0%7D: 
 time upd
@@ -375,16 +375,30 @@
 pdated.%22
+.format(rtime)
 %0A%0A%0Adef m
@@ -1387,16 +1387,101 @@
 stTime'%5D
+%0AreadableTime = arrow.utcnow().to(%0A    'US/Pacific').format(%22YYYY-MM-DD HH:mm:ss ZZ%22)
 %0A%0A# init
@@ -2162,18 +2162,146 @@
     
-print each
+ert = %22unknown title%22%0A            print %22%7B0%7D: unknown title: %7B1%7D%22.format(%0A                readableTime,%0A                each%0A            )
 %0A   
@@ -2336,37 +2336,18 @@
        e
-ach%5B'resolved_title'%5D
+rt
 ,%0A      
@@ -2542,16 +2542,21 @@
  print %22
+%7B1%7D: 
 made ste
@@ -2573,16 +2573,37 @@
 .format(
+%0A                    
 unidecod
@@ -2620,16 +2620,50 @@
 e(title)
+,%0A                    readableTime
 )%0A      
@@ -2712,16 +2712,21 @@
  print %22
+%7B0%7D: 
 no artic
@@ -2735,16 +2735,37 @@
 s found%22
+.format(readableTime)
 %0A%0A# set 
@@ -2803,10 +2803,22 @@
 eTimeDb(
+readableTime
 )%0A

fix logging to include timestamps