#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 Gregorio Robles
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# Authors:
#     Gregorio Robles <grex@gsyc.urjc.es>
#

import argparse
import logging
import sys

import git2effort
import git2effort.effort
import git2effort._version


GIT2EFFORT_USAGE_MSG = \
"""%(prog)s [-g] [<args>] <git_repository> | --help | --version"""

GIT2EFFORT_DESC_MSG = \
"""Calculate development effort estimation from a Git repository.

optional arguments:
  -g, --debug           set debug mode on
  -h, --help            show this help message and exit
  -v, --version         show version
"""


GIT2EFFORT_EPILOG_MSG = \
"""Visit http://github.com/gregoriorobles/git2effort for further information."""

GIT2EFFORT_VERSION_MSG = \
"""%(prog)s """  + git2effort._version.__version__


# Logging formats
GIT2EFFORT_LOG_FORMAT = "[%(asctime)s] - %(message)s"
GIT2EFFORT_DEBUG_LOG_FORMAT = "[%(asctime)s - %(name)s - %(levelname)s] - %(message)s"


def main():
    args = parse_args()
    
    configure_logging(args.debug)

    logging.info("git2effort starting.")

    git2effort.effort.run(vars(args))

    logging.info("git2effort finished.")


def parse_args():
    """Parse command line arguments"""

    parser = argparse.ArgumentParser(usage=GIT2EFFORT_USAGE_MSG,
                                     description=GIT2EFFORT_DESC_MSG,
                                     epilog=GIT2EFFORT_EPILOG_MSG,
                                      formatter_class=argparse.RawDescriptionHelpFormatter,
                                     add_help=False)

    parser.add_argument('-h', '--help', action='help',
                        help=argparse.SUPPRESS)
    parser.add_argument('-v', '--version', action='version',
                        version=GIT2EFFORT_VERSION_MSG,
                        help=argparse.SUPPRESS)
    parser.add_argument('-g', '--debug', dest='debug',
                        action='store_true',
                        help=argparse.SUPPRESS)
                        
    parser.add_argument("git_repository", help="URL of the Git repository you want to estimate development effort")

    parser.add_argument('-t', '--threshold', type=int, default=75, help='Threshold value (in commits) to determine if a developers is full-time devoted to the project. Default=75.')

    parser.add_argument('-p', '--period', type=int, default=6, help='Length of the time period  (in months). Default=6.')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    return parser.parse_args()

def configure_logging(debug=False):
    """Configure git2effort logging

    The function configures the log messages produced by git2effort.
    By default, log messages are sent to stderr. Set the parameter
    `debug` to activate the debug mode.

    :param debug: set the debug mode
    """
    if not debug:
        logging.basicConfig(level=logging.INFO,
                            format=GIT2EFFORT_LOG_FORMAT)
        logging.getLogger('requests').setLevel(logging.WARNING)
        logging.getLogger('urrlib3').setLevel(logging.WARNING)
    else:
        logging.basicConfig(level=logging.DEBUG,
                            format=GIT2EFFORT_DEBUG_LOG_FORMAT)


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        s = "\n\nReceived Ctrl-C or other break signal. Exiting.\n"
        sys.stderr.write(s)
        sys.exit(0)
