#!/usr/bin/env python3

import argparse
import curses
#import logging
import minorimpact
import os
import sys

import zlinklib

def main(stdscr):
    # I like 'vi', so that's the default editor.
    if ('EDITOR' not in os.environ):
        os.environ.setdefault('EDITOR', 'vi')


    #logging.basicConfig(level=logging.DEBUG, filename="./zlink.log")
    #logging.debug("-------")
    stdscr.clear()

    parser = argparse.ArgumentParser(description="Peruse and maintain a collection of Zettelkasten files in the current directory.")
    parser.add_argument('filename', nargs="?")
    parser.add_argument('--addlink', help = "add a link to ADDLINK to filename")
    parser.add_argument('--nobacklink', help = "when adding a link, don't create a backlink from filename to ADDLINK", action='store_true')
    parser.add_argument('--defrag', help = "update the zettelkasten files to remove any gaps between entries", action='store_true')
    args = parser.parse_args()

    if (args.addlink is not None and args.filename is not None):
        # Don't look at anything, just create a link from one file to another.
        note1 = zlinklib.Notes(args.filename)
        note2 = zlinklib.Note(args.addlink)
        note1.addnotelink(note2)
        note1.write()
        stdscr.addstr(f"Added link {note2.title} to {note1.title}\n")
        if (args.nobacklink is False):
            note2.addnotebacklink(note1)
            note2.write()
            stdscr.addstr(f"Added backlink {note1.title} to {note2.title}\n")
        stdscr.refresh()
        sys.exit()
    elif (args.defrag is True):
        # Make this fix all the files so that there are no duplicate orders
        #  and no holes
        files = zlinklib.loadnotes()
        for i in range(0, len(files)):
            note = None
            try:
                note = zlinklib.Note(files[i])
            except:
                raise Exception(f"Can't open '{files[i]}'")

            if (note.order != i+1):
                original_file = note.filename
                note.updateorder(i+1)
                stdscr.addstr(f"Moved {original_file} to {note.filename}\n")
                files[i] = note.filename

                for f in files:
                    n = zlinklib.Note(f)
                    n.updatelinks(original_file, note.filename)
        stdscr.refresh()
        sys.exit()

    n = zlinklib.NoteBrowser()
    n.browse(stdscr, args.filename)

#######
# START
#######

if __name__ == "__main__":
    # Hitting escape bungs everything up for a second; this reduces the delay.
    os.environ.setdefault('ESCDELAY', '15')
    curses.wrapper(main)
