#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#   snippet - Save status snippets
#   Author: Chris Ward <cward@redhat.com>
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#   Copyright (c) 2012 Red Hat, Inc. All rights reserved.
#
#   This copyrighted material is made available to anyone wishing
#   to use, modify, copy, or redistribute it subject to the terms
#   and conditions of the GNU General Public License version 2.
#
#   This program is distributed in the hope that it will be
#   useful, but WITHOUT ANY WARRANTY; without even the implied
#   warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
#   PURPOSE. See the GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public
#   License along with this program; if not, write to the Free
#   Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
#   Boston, MA 02110-1301, USA.
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"""
Comfortably save your status snippets (e.g. task or activity)
completed on a given date.
"""

from __future__ import unicode_literals, absolute_import

import ConfigParser
from getpass import getuser
import argparse
import sys

from status_report.utils import Config, ConfigError, CONFIG, Date
from status_report.utils import info, pretty, log
from status_report.sniprepo import SnippetsRepoSQLAlchemy

TODAY = str(Date("today"))
USER_DEFAULT = getuser()

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#  Options
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


class Options(object):
    """ Command line options parser """
    def __init__(self):
        """ Prepare the parser. """
        parser = argparse.ArgumentParser(
            usage="./snippet topic [YYYY-MM-DD] snippet ...",
            description=__doc__.strip())

        parser.add_argument(
            'topic',
            help="Which topic group does this snippet below too?")

        parser.add_argument(
            'snippets',
            nargs='*',
            help="Snippet text")

        storage = parser.add_argument_group("Storage")
        storage.add_argument(
            "-u", "--uri",
            help="Override the Snippets storage backend uri (path)")

        # Display / Debug options
        display = parser.add_argument_group("Display / Debug")
        display.add_argument(
            "--debug", "-d",
            action="store_true",
            help="Turn on debugging output, do not catch exceptions")

        self.config = Config()
        self.parser = parser

    def parse(self):
        """ Parse the options. """
        args = self.parser.parse_args()

        # Enable debugging output
        if args.debug:
            log.setLevel(level=2)

        # extract the topic destination uri from the snippets group
        for section in self.config.sections(kind='snippet'):
            if args.topic in dict(self.config.section(section)).keys():
                args.uri = dict(self.config.section(section))[args.topic]
                break
        else:
            raise ConfigError("Invalid topic: {0}".format(args.topic))

        if args.snippets:
            # merge everything into a single string
            snippets = ' '.join(args.snippets).strip()
            snippets = [snippets]
        else:  # get the snippets from the user input
            snippets = []
            info("Add your snippet(s), then CTRL-D:")
            while True:
                try:
                    input_str = raw_input(">").strip()
                except (EOFError, KeyboardInterrupt):
                    break
                else:
                    # ignore empty lines
                    if input_str:
                        snippets.append(input_str)

        if not snippets:
            log.warn("No Snippets Added")
            sys.exit(0)

        # Finito
        log.debug("Gathered options:")
        log.debug(pretty(args))
        log.debug("{0} snippet(s) gathered".format(len(snippets)))
        log.debug(snippets)
        return args, snippets


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#  Main
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

def main():
    try:
        # Parse options
        args, snippets = Options().parse()
    except ConfigParser.NoSectionError as e:
        log.error(e)
        log.error("No email provided on the command line or in the config file")
        info("Create at least a minimum config file {0}:".format(CONFIG))
        info('[general]\nemail = "My Name" <{0}@domain.com>'.format(getuser()))
        sys.exit(3)

    uri = args.uri
    debug = args.debug

    snippets = SnippetsRepoSQLAlchemy(snippets=snippets, uri=uri, debug=debug,
                                      topic=args.topic)
    snippets.parse_snippets(snippets)
    snippets.write()


if __name__ == "__main__":
    main()
