#coding: utf-8
'''
python3
pyt_xcall_root.py
2017-04-08 at 21:01 EDT

Sample script for testing Pythonists with x-callback-url and Ulysses 2.8

Use WorkFlow.app to initiate this script: https://workflow.is/workflows/f340b93c7c344e9a859a53d62fec22dd

It makes a complete list of all sheets in all groups and libraries,
and finally opens the Markdown result as a new sheet in Ulysses.
'''

import webbrowser
import json
import datetime
import urllib.parse
import sys

time_stamp = datetime.datetime.now().strftime("%Y-%m-%d at %H:%M")


def main():
    '''Main funcion.'''
    result = []
    result.append("# Ulysses library report")
    result.append("_Processed in Pythonista " + time_stamp + "_")
    input = 'no input'
    if len(sys.argv) > 1:
        input = sys.argv[1]
        # print(input)
    else:
        print(input)
        quit()
    group_json_tree = json.loads(input)

    process_containers(result, group_json_tree, "", "")

    # Sending result to Ulysses:
    md_text = "\n".join(result)
    url = "ulysses://x-callback-url/new-sheet?text=" + urllib.parse.quote(md_text)
    webbrowser.open(url)


def process_containers(result, items, path, heading):
    '''Recursive function to iterate json tree.'''
    heading += "#"
    for item in items:
        title = item["title"]
        if path == '':
            if title == "iCloud" or title == "On My Mac":
                sub_path = title
            else:
                sub_path = "Dropbox:" + title
        else:
            sub_path = path + "/" + title

        if item["type"] == "filter":
            result.append("\n* _Filter: " + sub_path + "_")
        else:
            result.append("\n" + heading + " " + sub_path)

        if "sheets" in item:
            process_sheets(result, item["sheets"])
        # Recursive call:
        process_containers(result, item["containers"], sub_path, heading)


def process_sheets(result, items):
    '''Extract available sheet info.'''
    count = 1
    for sheet in items:
        mod_date = date_conv(sheet["modificationDate"])
        if len(sheet["title"]) > 50:
            tail = "..."
        else:
            tail = ""
        details = " _" + mod_date + "_"
        line = str(count) + ". " + sheet["title"][:50] + tail + details
        # print(line)
        result.append(line)
        count += 1


def date_conv(dtnum):
    '''Get date from secconds Ulysses gives secconds from 2001-01-01 00:00
       had to adjust for pyton's different seed date'''
    dtdate = datetime.datetime.fromtimestamp(dtnum + 31*365*24*3600 + 24*3600*8)
    return dtdate.strftime('%Y-%m-%d')


if __name__ == '__main__':
    main()