#!/usr/bin/env python
import os
import sys

from colorama import init
from colorama import Fore, Back, Style
from prettytable import PrettyTable

from yhat import project
from yhat import credentials

init()

PROJECT_DIR = os.path.join(os.environ['HOME'], ".yhat/templates")


def prompt_user():
    choices = []
    if os.path.isdir(PROJECT_DIR):
        for f in os.listdir(PROJECT_DIR):
            if f.endswith(".json"):
                choices.append(f[:-5])

    choices.append('*new project*')
    choices.append('*download template*')

    choices_lookup = {}
    print "" + Fore.CYAN
    table = PrettyTable([Fore.CYAN + "", Fore.CYAN + "Template"])
    for i, choice in enumerate(choices):
        choices_lookup[str(i+1)] = choice
        table.add_row([
            Fore.CYAN + "(%d)" % (i+1),
            Fore.CYAN + choice
        ])
    print table
    return choices_lookup.get(raw_input("(?) "))


if __name__=="__main__":
    if sys.argv[1]=="new":
        result = prompt_user()
        while result is None:
            result = prompt_user()
        
        print Fore.GREEN + result
        project.setup(result, result)
    elif sys.argv[1]=="fetch":
        print "Downloading template %s" % (Fore.YELLOW + os.path.basename(sys.argv[2]) + Fore.RESET + " ")
        project.download_template(sys.argv[2])
    elif sys.argv[1]=="config":
        if len(sys.argv) > 2:
            if sys.argv[2]=="reset":
                # save the user's credentials in a dotfile
                credentials.setup()
        else:
            # print out the user's saved config
            table = PrettyTable(["Key", "Value"])
            for key, value in credentials.read().items():
                table.add_row([key, value])
            print table

    elif sys.argv[1]=="bundle":
        project_name = sys.argv[2]
        directory = sys.argv[3]
        project.bundle(project_name, directory)

