#!/usr/bin/env python3

import sys
import subprocess


MAX_LOG = 2
MAX_BRANCH = 7

def read_arguments():
	passed_name = "" if len(sys.argv) <= 1 else sys.argv[1]
	if passed_name == "--reset":
		passed_name = ""
	return passed_name, MAX_BRANCH, MAX_LOG
			

def get_branch_index(limit):
	str = input("Branch? ")
	if not str is None:
		try: 
			num = int(str)
			if num > 0 and num <= limit:
				return num
		except:
			return get_branch_index(limit)
	return get_branch_index(limit)

def green(string):
    return '\x1b[0;32;40m' + string + '\x1b[0m'    
	
RESET = "--reset" in sys.argv
	
def main():
	passed_name, max_branch, max_log = read_arguments()
	found = [x for x in subprocess.check_output(["git","branch","--sort=-committerdate"]).decode().replace(" ", "").split("\n") if x != '' and x.find(passed_name) > -1]
	if len(found) > 0:
		if len(found) > max_branch:
			found = found[:max_branch]
		print(green("BRANCHES") + ":")
		enum = enumerate(found, 1)
		current = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]).decode().replace("\n", "")
		for i, b in enum:
			the_branch =  b if current != b[1:] else current
			if the_branch.startswith("+"):
				the_branch = the_branch[1:]
			log = subprocess.check_output(["git", "log" , "--pretty=format:%ad %Cred%h %Creset%s", "-n", str(MAX_LOG), "--date=format:%Y-%m-%d %H:%M:%S","%s" % the_branch]).decode()
			print((green("\n({})")+ " {}\t ").format(i, b))
			print("\t"  + "\n\t".join(log.split("\n")))
			

		a = get_branch_index(max_branch)
	
		subprocess.check_output(["git","checkout","%s" % found[a-1] if found[a-1][1:] != current else current])
		if RESET:
			import os
			os.system("git rh")
	else:
		import os
		print("Nothing found, let's create branch for issue: [%s]" % passed_name)
		os.system("git nb " + passed_name)

if __name__ == "__main__":
	exit_value = main()
