#!/usr/bin/env python
import os
import sys
import subprocess
from textwrap import dedent

DEFAULT_CHEAT_DIR = os.environ.get('DEFAULT_CHEAT_DIR') or \
                    os.path.join(os.path.expanduser('~'), '.cheat')
USE_PYGMENTS      = False

# NOTE remove this check if it is confirmed to work on windows
if os.name == 'posix' and 'CHEATCOLORS' in os.environ:
    try:
        from pygments import highlight
        from pygments.util import ClassNotFound
        from pygments.lexers import get_lexer_for_filename, TextLexer
        from pygments.formatters import TerminalFormatter
        USE_PYGMENTS = True
    except ImportError:
        pass


def cheat_directories():
    "Assembles a list of directories containing cheatsheets."
    default_directories = [DEFAULT_CHEAT_DIR]
    try:
        import cheatsheets
        default_directories.append(cheatsheets.cheat_dir)
    except ImportError:
        pass

    default = [default_dir for default_dir in default_directories
               if os.path.isdir(default_dir)]

    if 'CHEATPATH' in os.environ and os.environ['CHEATPATH']:
        return [path for path in os.environ['CHEATPATH'].split(os.pathsep)
                if os.path.isdir(path)] + default
    else:
        return default


def cheat_files(cheat_directories):
    "Assembles a dictionary of cheatsheets found in the above directories."
    cheats = {}
    for cheat_dir in reversed(cheat_directories):
        cheats.update(dict([(cheat, cheat_dir)
                            for cheat in os.listdir(cheat_dir)
                            if not cheat.startswith('.')
                            and not cheat.startswith('__')]))
    return cheats


def edit_cheatsheet(cheat, cheatsheets):
    "Creates or edits a cheatsheet"

    # Assert that the EDITOR environment variable is set and that at least 3
    # arguments have been given
    if 'EDITOR' not in os.environ:
        print('In order to use "create" or "edit" you must set your '
              'EDITOR environment variable to your favorite editor\'s path')
        exit()

    elif len(sys.argv) < 3:
        print ('Must provide a cheatsheet to edit/create')
        exit()

    # if the cheatsheet already exists, open it for editing
    if cheat in cheatsheets:
        subprocess.call([os.environ['EDITOR'],
                      os.path.join(cheatsheets[cheat], cheat)])

    # otherwise, create it
    else:
        import cheatsheets as cs
        # Attempt to write the new cheatsheet to the user's ~/.cheat dir if it
        # exists. If it does not exist, attempt to create it.
        if os.access(DEFAULT_CHEAT_DIR, os.W_OK) or os.makedirs(DEFAULT_CHEAT_DIR):
            subprocess.call([os.environ['EDITOR'],
                            os.path.join(DEFAULT_CHEAT_DIR, cheat)])

        # If the directory cannot be created, write to the python package
        # directory, though that will likely require the use of sudo
        else:
            subprocess.call([os.environ['EDITOR'],
                            os.path.join(cs.cheat_dir, cheat)])


def help(cheatsheets):
    "Displays the program help"

    print dedent('''
        Usage: cheat [OPTIONS] <keyphrase>
        Examples:

        To look up 'tar':
        cheat tar

        To look up 'git commit' (a subcommand):
        cheat git commit

        To edit or edit the cheatsheet for 'foo':
        cheat -e foo

        Available keyphrases:
    ''').strip()

    print list_cheatsheets(cheatsheets)
    exit()


def list_cheatsheets(cheatsheets):
    max_command = max([len(x) for x in cheatsheets.keys()]) + 3
    return ('\n'.join(sorted(['%s [%s]' % (key.ljust(max_command), value)
                            for key, value in cheatsheets.items()])))


def pretty_print(filename):
    "Applies syntax highlighting to a cheatsheet and writes it to stdout"
    try:
        if os.path.splitext(filename)[1]:
            lexer = get_lexer_for_filename(filename)
        else:
            # shell is a sensible default when there is no extension
            lexer = get_lexer_for_filename(filename + '.sh')

    except ClassNotFound:
        lexer = TextLexer()

    with open(filename) as istream:
        code = istream.read()

    fmt = TerminalFormatter()
    highlight(code, lexer, fmt, sys.stdout)


def main():
    # assemble a keyphrase out of all params passed to the script
    keyphrase  = ' '.join(sys.argv[1:])
    cheat_dirs = cheat_directories()

    # verify that we have at least one cheat directory
    if not cheat_dirs:
        error_msg = 'The {default} dir does not exist or the CHEATPATH var is not set.'
        print >> sys.stderr, error_msg.format(default=DEFAULT_CHEAT_DIR)
        exit()

    # list the files in the ~/.cheat directory
    cheatsheets = cheat_files(cheat_dirs)

    # @TODO: refactor the below into argparse

    # print help
    if keyphrase in ['', 'cheat', 'help', '-h', '-help', '--help']:
        help(cheatsheets)
        exit()

    # list cheat directories and exit
    if keyphrase in ['-d', '--cheat-directories']:
        print("\n".join(cheat_directories()))
        exit()

    # list cheatsheets and exit
    if keyphrase in ['-l', '--list']:
        print list_cheatsheets(cheatsheets)
        exit()

    # if the user wants to edit a cheatsheet
    if (sys.argv[1]) and (sys.argv[1] in ['-e', '--edit']):
        edit_cheatsheet(' '.join(sys.argv[2:]), cheatsheets)
        exit()

    # print the cheatsheet if it exists
    if keyphrase in cheatsheets:
        filename = os.path.join(cheatsheets[keyphrase], keyphrase)
        if USE_PYGMENTS:
            pretty_print(filename)
        else:
            with open(filename) as istream:
                for l in istream:
                    sys.stdout.write(l)

    # if it does not, say so
    else:
        print ('No cheatsheet found for %s.' % keyphrase)


if __name__ == '__main__':
    main()