#!python
# -*- coding: utf-8 -*-

import sys
import os
import os.path
import subprocess
from datetime import datetime
import EtnaAPI
import EtnaAPI.Authentication
import EtnaAPI.Todos

branch_types = {
    "hf": "bug",
    "fix": "bug",
    "feature": "feature",
    "cr": "refactoring"
}

def get_resource_filename(name):
    import pkg_resources
    return pkg_resources.resource_filename('jawa-repo-hooks', os.path.join('hooks', name))

def ensure(cond, err_msg):
    if not cond:
        print(err_msg, file=sys.stderr)
        exit(1)


def get_git_top_level_dir():
    return subprocess.check_output(["git", "rev-parse", "--show-toplevel"]).decode("utf-8").strip()


def setup():
    files = ["prepare-commit-msg", "commit-msg", "post-commit", "post-rewrite", "post-checkout", "post-merge"]
    for f in files:
        try:
            os.symlink(get_resource_filename(f), os.path.join(get_git_top_level_dir(), '.git', 'hooks', f))
        except FileExistsError:
            pass
    print("Yay repo is ready to roll")


def start(branch_type, ticket_id):
    ensure(branch_type in branch_types.keys(), "Branch types must be hf, fix, feature or cr")
    os.system("git fetch")
    os.system("git checkout -b {}/{} origin/master".format(branch_type, ticket_id))


def create_then_start(branch_type):
    ensure(branch_type in branch_types.keys(), "Branch types must be hf, fix, feature or cr")
    repo_name = get_git_top_level_dir().split('/')[-1]
    todo = {
        "title": "[" + repo_name + "] " + branch_types[branch_type],
        "users": [],
        "ttl": datetime.today().strftime('%Y-%m-%d'),
        "tags": [branch_types[branch_type], repo_name],
        "message": "a"
    }
    session = EtnaAPI.Session()
    auth_src = EtnaAPI.Authentication.KeyringAuthenticator()
    auth_src.authenticate(session)
    todo_controller = EtnaAPI.Todos.Controller(session)
    resp = todo_controller.create_todo(todo)
    ticket_id = resp["id"]
    print("Successfully created todo #{}".format(ticket_id))
    start(branch_type, ticket_id)


ensure(len(sys.argv) >= 2, "Usage:\n\trepo start <feature> <ticket>\n\trepo setup")

if sys.argv[1] == "setup":
    setup()
elif sys.argv[1] == "start":
    ensure(len(sys.argv) >= 3, "Usage: repo start <type> <ticket_id>")
    if sys.argv[2] == "--complete":
        print('\n'.join(branch_types.keys()))
    else:
        if len(sys.argv) == 4:
            start(sys.argv[2], sys.argv[3])
        else:
            create_then_start(sys.argv[2])
else:
    ensure(False, "Usage:\n\trepo start <commit type> <ticket>\n\trepo setup")
