# File generated by Setupinit
import sys
import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
from exonote import Viewer, constant, split_target
from exonote.editor import Editor


TEXT = """\
Welcome to Pyrustic Exonote !
Write down and render notes embedding programs

Usage:
    exonote <filename>
    exonote <option> [<arg> ...]
    
Options:
    -r, --restrict <filename>   Open a note with low restriction
    -R, --Restrict <filename>   Open a note with high restriction
    -h, --help                  Show help text

Note:
    Open a note with restriction when you don't trust the author !
    Low restriction: block the execution of embedded programs.
    High restriction: same as low restriction + block executable links
    
Visit the webpage: https://github.com/pyrustic/exonote\
"""


def main():
    args = sys.argv[1:]
    if not args:
        print(TEXT)
        return
    command = args[0]
    if command in ("-h", "--help"):
        print(TEXT)
    elif command in ("-r", "--restrict", "-R", "--Restrict"):
        restriction = constant.LOW
        if command in ("-R", "--Restrict"):
            restriction = constant.HIGH
        if len(args) != 2:
            print("You need to append a filename to this command.")
            return
        filename = args[1]
        open_gui(filename, restriction=restriction)
    else:
        filename = command
        open_gui(filename)


def open_gui(filename, restriction=0):
    root = tk.Tk()
    root.title("Pyrustic Exonote")
    root.config(bg="white")
    ttkstyle = ttk.Style()
    set_scrollbar_style(ttkstyle)
    editor = Editor(root, width=80, borderwidth=0, highlightthickness=0)
    editor.pack(expand=True, fill=tk.BOTH, padx=(10, 0))
    viewer = Viewer(editor, restriction=restriction, on_open=on_open)
    if not viewer.open(filename):
        print("This file doesn't exist.")
        return
    editor.focus_set()
    root.bind("<F5>", lambda e: on_refresh(viewer))
    root.mainloop()


def on_open(viewer, path):
    x = split_target(path)
    if not x:
        return
    path = x[0]
    cache = path[0:50] + "..." if len(path) > 50 else path
    title = "{}  |  Pyrustic Exonote".format(cache)
    root = viewer.editor.nametowidget(".")
    root.title(title)
    return path


def on_refresh(viewer):
    viewer.refresh()
    viewer.statusbar.show("Refreshed !", delay=0, duration=1000)


def set_scrollbar_style(ttkstyle):
    ttkstyle.configure("TScrollbar", relief="flat", borderwidth=0,
                       troughcolor="white", width=11, arrowsize=0,
                       background="#E7E7E7")
    ttkstyle.map("TScrollbar",
                 background=[("active", "#D1D1D1")],
                 troughcolor=[("active", "#F4F4F4")])


if __name__ == "__main__":
    main()
