#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''gig

A .gitignore template generator.

Usage:
  gig list
  gig <language> ... [--append --force --verbose]
  gig Python Ruby Clojure ...

Options:
  -h --help             Show this screen.
  --version             Show version.
  list                  List available languages. NOTE: Languages are case-sensitive.
  -a --append           If .gitignore already exists, append to it.
  -f --force            If .gitignore already exists, overwrite it.
  -v --verbose          Toggle verbose output.
'''

import os
import sys
import logging
from docopt import docopt
import requests

__version__ = "0.1.0"
__author__ = "Steven Loria"
__license__ = "MIT"

API_URL = "https://api.github.com/gitignore/templates"
TEMPLATE_URL = 'https://raw.github.com/github/gitignore/master'
HEADER = "########## Generated by gig {0} ###########\n".format(__version__)

def generate_gitignore(languages):
    '''Return the .gitignore (a string) given a list of languages.'''
    gitignore = ''
    session = requests.Session()
    for language in languages:
        url = TEMPLATE_URL + "/" + language + '.gitignore'
        res = session.get(url)
        if res.status_code == requests.codes.ok:
            content = res.text  # The gitignore template
            gitignore = '\n'.join([gitignore,
                                    "### {0} ###".format(language),
                                    content])
            logging.info("Ignoring {0}. . .".format(language))
        else:
            logging.debug(res.status_code)
            message = ("Couldn't get .gitignore for {0}. NOTE: Languages "
                        "are case-sensitive.".format(language))
            logging.error(message)
            continue
    return gitignore

def list_languages():
    '''Output the list of available languages.'''
    res = requests.get(API_URL)
    ok = res.status_code == requests.codes.ok
    if ok:
        languages = res.json()
        for language in languages:
            print(language)
    else:
        logging.debug(res.status_code)
        logging.error("Couldn't get language list. Please try again later.")
        return False
    return ok

def main():
    '''Main entry point for the gig CLI.'''
    args = docopt(__doc__, version=__version__)
    log_level = logging.INFO if args['--verbose'] else logging.ERROR
    logging.basicConfig(format='%(levelname)s: %(message)s', level=log_level)
    if args['list']:
        success = list_languages()
        return sys.exit(0) if success else sys.exit(1)
    languages = args['<language>']
    if os.path.isfile(".gitignore") and not args['--force']\
                                    and not args['--append']:
        logging.error(".gitignore already exists in this directory. "
                        "Use the '--force' option to force overwrite or "
                        "'--append' to append to the file.")
        print(__doc__)
        return sys.exit(1)
    write_mode = 'a' if args['--append'] else 'w'
    with open(".gitignore", write_mode) as fp:
        if not args['--append']:
            fp.write(HEADER)
        fp.write(generate_gitignore(languages))
    print("Done.")
    return sys.exit(0)

if __name__ == '__main__':
    main()