#!/usr/bin/env python
'''
command module for Not
provides the `not` executable
hint: 'f' always refers to the temp file
      'n' is the evernote api wrapper "notpy.Note()"
'''
import argparse
import hashlib
import tempfile
import re
from datetime import date
from subprocess import call
from notpy import NotClient, config

try:
    not_client = NotClient(token=config.TOKEN, sandbox=False)
except:
    print "bailing!"
    print "you may need to run `not-setup` and try again"
    import sys; sys.exit(1)


def md5sum(f):
    '''
    simply returns an md5sum of the contents of your note
    '''
    return hashlib.md5(open(f).read()).hexdigest()


def check_existing(title, f):
    '''
    checks if your note already exists based on title
    if it does, grabs the contents so we can append
    '''
    note = not_client.search(title)
    if note:
        content = re.sub('<br/>', '\n',not_client.get_content(note))
        content = re.sub('<.*?>', '', content)
        #content = content + '\n'
        open(f, 'w').write(content)
    return f


def note_save_error(e, guts):
    print 'failed to save note!\n\n'
    print 'exception was: {0}\n\n'.format(e)
    print 'contents of unsaved note: \n\n'
    print guts


def cli():
    '''
    opens or creates the note, uses today's date or an explicit title
    '''
    parser = argparse.ArgumentParser(description='not')
    parser.add_argument('title', nargs='?', default=str(date.today()))
    args = vars(parser.parse_args())

    with tempfile.NamedTemporaryFile(suffix=config.SUFFIX) as f:
        check_existing(args['title'], f.name)
        md5 = md5sum(f.name)
        call([config.EDITOR, '+', f.name])
        if md5sum(f.name) != md5:
            guts = open(f.name).read().strip()
            try:
                not_client.save(guts, title=args['title'])
            except Exception as e:
                note_save_error(e, guts)

@@ -227,16 +227,27 @@
 port re%0A
+import sys%0A
 from dat
@@ -490,20 +490,8 @@
 %0A   
- import sys;
  sys
@@ -639,24 +639,256 @@
 xdigest()%0A%0A%0A
+def format_to_plain_text(content):%0A    '''%0A    Given the contents of an existing note, strip out all the HTML tags%0A    '''%0A    content = re.sub('%3Cbr/%3E', '%5Cn', content)%0A    content = re.sub('%3C.*?%3E', '', content)%0A    return content%0A%0A%0A
 def check_ex
@@ -1094,37 +1094,37 @@
 ntent = 
-re.sub('%3Cbr/%3E', '%5Cn',
+format_to_plain_text(
 not_clie
@@ -1149,89 +1149,8 @@
 e))%0A
-        content = re.sub('%3C.*?%3E', '', content)%0A        #content = content + '%5Cn'%0A
     
@@ -1630,16 +1630,124 @@
 rgs())%0A%0A
+    if sys.stdin.isatty():%0A        # Nothing is being piped in, so open a file and let the user edit it%0A    
     with
@@ -1807,24 +1807,28 @@
  f:%0A        
+    
 check_existi
@@ -1861,16 +1861,20 @@
         
+ 
+   
 md5 = md
@@ -1878,32 +1878,36 @@
  md5sum(f.name)%0A
+    
         call(%5Bco
@@ -1941,16 +1941,20 @@
         
+   
+ 
 if md5su
@@ -1971,16 +1971,20 @@
 != md5:%0A
+    
         
@@ -2034,16 +2034,20 @@
         
+    
 try:%0A   
@@ -2055,24 +2055,28 @@
             
+ 
+   
 not_client.s
@@ -2118,16 +2118,20 @@
         
+    
 except E
@@ -2157,24 +2157,28 @@
             
+   
+ 
 note_save_er
@@ -2190,8 +2190,516 @@
 , guts)%0A
+    else:%0A        # The user is trying to pipe things in through stdin%0A        existing_note_guid = not_client.search(args%5B'title'%5D)%0A        if existing_note_guid:%0A            content = format_to_plain_text(%0A                not_client.get_content(existing_note_guid))%0A        else:%0A            content = ''%0A%0A        content += '%5Cn'.join(line for line in sys.stdin)%0A%0A        try:%0A            not_client.save(content, title=args%5B'title'%5D)%0A        except Exception as e:%0A            note_save_error(e, content)%0A

allow users to pipe content to `not` through stdin