#!/usr/bin/env python2
"""A fast note-taking app for the UNIX terminal"""

import argparse
import configparser
import os
import logging
import logging.handlers
import sys

import tv2.urwid_ui as urwid_ui


def main():

    # Parse the command-line option for the config file.
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument("-c", "--config", dest="config", action="store",
            default="~/.tvrc",
            help="the config file to use (default: %(default)s)")
    args, remaining_argv = parser.parse_known_args()

    # Parse the config file.
    config_file = os.path.abspath(os.path.expanduser(args.config))
    config = configparser.SafeConfigParser()
    config.read(config_file)
    defaults = dict(config.items('DEFAULT'))

    # Parse the rest of the command-line options.
    description = __doc__
    epilog = """
the config file can be used to override the defaults for the optional
arguments, example config file contents:

    [DEFAULT]
    editor = vim
    # The filename extension to use for new files.
    extension = .txt
    # The filename extensions to recognize in the notes dir.
    extensions = .txt, .text, .md, .markdown, .mdown, .mdwn, .mkdn, .mkd, .rst
    notes_dir = ~/Notes

if there is no config file (or an argument is missing from the config file)
the default default will be used"""

    parser = argparse.ArgumentParser(description=description, epilog=epilog,
            parents=[parser],
            formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("-e", "--editor", dest="editor", action="store",
        default=defaults.get("editor", os.getenv("EDITOR", "vim")),
        help="the text editor to use (default: %(default)s)")

    parser.add_argument("-x", "--extension", dest="extension", action="store",
        default=defaults.get("extension", "txt"),
        help="the filename extension for new notes (default: %(default)s)")

    parser.add_argument("--extensions", dest="extensions", action="store",
        default=defaults.get("extensions",
            ".txt, .text, .md, .markdown, .mdown, .mdwn, .mkdn, .mkd, .rst"),
        help="the filename extensions to recognize in the notes dir, a "
            "comma-separated list (default: %(default)s)")

    parser.add_argument("--exclude", dest="exclude", action="store",
        default=defaults.get("exclude",
            "src, backup, ignore, tmp, old"),
        help="the file/directory names to skip while recursively searching "
            "the notes dir for notes, a comma-separated list "
            "(default: %(default)s)")

    parser.add_argument("-d", "--debug", dest="debug", action="store_true",
        default=defaults.get("debug", False),
        help="debug logging on or off (default: off)")

    parser.add_argument("-l", "--log-file", dest="log_file", action="store",
        default=defaults.get("log_file", "~/.tvlog"),
        help="the file to log to (default: %(default)s)")

    parser.add_argument("-p", "--print-config", dest="print_config",
            action="store_true", default=False,
            help="print your configuration settings then exit")

    parser.add_argument("notes_dir", action="store", nargs="?",
        default=defaults.get("notes_dir", "~/Notes"),
        help="the notes directory to use (default: %(default)s)")

    args = parser.parse_args()

    extensions = []
    for extension in args.extensions.split(","):
        extensions.append(extension.strip())
    args.extensions = extensions

    exclude = []
    for name in args.exclude.split(","):
        exclude.append(name.strip())
    args.exclude = exclude

    if args.print_config:
        print(args)
        sys.exit()

    logger = logging.getLogger("tv2")
    # Send all messages to handlers, let them decide.
    logger.setLevel(logging.DEBUG)
    fh = logging.handlers.RotatingFileHandler(
                os.path.abspath(os.path.expanduser(args.log_file)),
                maxBytes=1000000,  # 1 megabyte.
                backupCount=0)
    if args.debug:
        fh.setLevel(logging.DEBUG)
    else:
        fh.setLevel(logging.WARNING)
    logger.addHandler(fh)
    sh = logging.StreamHandler(sys.stdout)
    sh.setLevel(logging.CRITICAL)
    logger.addHandler(sh)

    logger.debug(args)

    try:
        urwid_ui.launch(notes_dir=args.notes_dir, editor=args.editor,
                extension=args.extension, extensions=args.extensions,
                exclude=args.exclude)
    except KeyboardInterrupt:
        # Silence KeyboardInterrupt tracebacks on ctrl-c.
        sys.exit()

if __name__ == "__main__":
    main()
