#coding: utf-8
'''
python3
md_split2ulysses_xcall.py
2017-04-07 at 09:55 EDT

Will take Markdown file as input or from clipboard and split it to Ulysses sheets
at chosen heading levels.
A new Ulysses group for these sheets will be created at root level.
'''

import subprocess
import json
import sys
import re
import urllib.parse

SPLIT_LEVEL = 2
ACCESS_TOKEN = "5a5887277e324caabb4e9229c79141b3"
XCALLAPP = "/Applications/xcall.app/Contents/MacOS/xcall"

X_NEW_GROUP = "ulysses://x-callback-url/new-group?name={name}"
X_NEW_SHEET = "ulysses://x-callback-url/new-sheet?groupId={id}&index={index}&text={text}"

arg1 = ""
if len(sys.argv) > 1:
    if sys.argv[1] != "":
        arg1 = sys.argv[1]


def main():
    if arg1 == "":
        md_text = read_from_clipboard()
    else:
        md_text = read_file(arg1)
    md_lines = md_text.splitlines()
    title = re.sub(r'^#+ ', '', md_lines[0])
    group_id = new_ul_group(title)
    pattern = '#' + '#?' * (SPLIT_LEVEL - 1) + " "
    break_points = []
    index = 1
    for line in md_lines[1:]:
        if re.match(pattern, line):
            print(line)
            break_points.append(index)
        index += 1
    break_points.append(len(md_lines))
    start = 0
    index = 0
    for end in break_points:
        print(str(index) + '. ' + md_lines[start])
        new_sheet(md_lines[start:end], group_id, index)
        start = end
        index += 1
    # View result group in Ulysses:
    url = "ulysses://x-callback-url/open-group?id=" + group_id
    subprocess.call(["open", url])
    # NOTE! subprocess.call() with "open" does not wait! So should only be used as last command!


def new_ul_group(title):
    print('New group = Splitted: ' + title)
    gr_name = urllib.parse.quote('Splitted: ' + title[:20])
    url = X_NEW_GROUP.format(name=gr_name)
    args = XCALLAPP + ' -url "' + url + '"'
    output = subprocess.check_output(args, shell=True)
    ret_dict = json.loads(output.decode('UTF-8'))
    return ret_dict['targetId']


def new_sheet(chunk, group_id, index):
    md_text = '\n'.join(chunk)
    url = X_NEW_SHEET.format(id=group_id, index=index, text=urllib.parse.quote(md_text))
    args = XCALLAPP + ' -url "' + url + '"'
    ret_code = subprocess.call(args, shell=True)
    if ret_code != 0:
        print('Error: ' + str(ret_code) + ': ' + chunk[1])


def read_from_clipboard():
    return subprocess.check_output(
        'pbpaste', env={'LANG': 'en_US.UTF-8'}).decode('utf-8')


if __name__ == '__main__':
    main()
