import json
import os

from dptrp1.dptrp1 import DigitalPaper

client_id=''
key=''
SYNC_DIR = '/home/dl92/Documents/DigitalPaper/'
def connect(address=''):
    """
    Loads the key and client ID to authenticate with the DPT-RP1
    """
    with open('/home/dl92/.dpt-client.txt', 'r') as f:
        client_id = f.readline().strip()

    with open('/home/dl92/.dpt-key.txt', 'r') as f:
        key = f.read()

    dpt = DigitalPaper(address)
    dpt.authenticate(client_id, key)
    return dpt

def sync(dpt):
    """
    Given an authenticated DigitalPaper instance, download all note files to a
    specified directory.
    """
    for doc in [f for f in dpt.list_documents() if (is_modified_note(f) and is_ReadingFolder(f)) ]:
        #docpath=os.path.dirname(doc['entry_path'])
        #if docpath=='Document/Reading' :
        data = dpt.download(doc['entry_path'])
        local_path = SYNC_DIR + os.path.basename(doc['entry_path'])
        with open(local_path, 'wb') as f:
            f.write(data)
        print('Saved {} to {}'.format(doc['entry_path'], local_path))
        
def is_modified_note(doc):
    import dateparser
    if doc['document_type'] == 'note' or doc['document_type'] == 'normal':
        local_path = SYNC_DIR + os.path.basename(doc['entry_path'])
        
        if not os.path.exists(local_path):
            return True
        else:
            #print (local_path,doc['modified_date'], os.path.getmtime(local_path), dateparser.parse(doc['modified_date']).timestamp())
            return os.path.getmtime(local_path) < dateparser.parse(doc['modified_date']).timestamp()
        
def is_ReadingFolder(doc):
    docpath=os.path.dirname(doc['entry_path'])
    if docpath=='Document/Reading':
        return True
    else:
        return False
        

def upload_overwrite(dpt,localpath, remotepath='Document/Reading'):
    import glob, os
    dpt.new_folder(remotepath)
    files= glob.glob(localpath+'/*.pdf')
    for f in files:
        print (f)
        dpt.upload_file(f,remotepath)

def delete_foldercontent(dpt,remotepath):
    [dpt.delete_document(doc['entry_path']) for doc in dpt.list_objects_in_folder(remotepath)]
        

dpt=connect('192.168.0.131')
#sync(dpt)
#dpt.new_folder('Document/Miri')
#upload_overwrite(dpt,SYNC_DIR+'/Upload','Document/Miri')
