#!/usr/bin/env python
# -*- coding:utf-8 -*-
# for hotelnow
import subprocess
import json
import sys

TRELLO_URL = 'https://api.trello.com/1/boards/5344b27268c2f3440862907b/cards/?key=8b330c0e445c6e3eee3e32f1a26a3c0b&token=3565d6f295030010bdca7fd25f22aa46cd417ec3bf4eb05fb0476953aa1b4c16'

class bcolors:
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    PURPLE = '\033[35m'
    SKYBLUE = '\033[36m'
    GREY = '\033[37m'
    WHITE = '\033[38m'

    COLOR_HASH = {
        'endc':ENDC,
        'underline':UNDERLINE,
        'bold':BOLD,
        'red':RED,
        'green':GREEN,
        'yellow':YELLOW,
        'blue':BLUE,
        'purple':PURPLE,
        'skyblue':SKYBLUE,
        'grey':GREY,
        'white':WHITE,
        'orange':SKYBLUE,
        'fail':RED,
        'warning':YELLOW,
        'normal':WHITE,
    }

    @staticmethod
    def set_ansi_color(string, color=None):
        return bcolors.COLOR_HASH.get(color,bcolors.WHITE) + string + bcolors.ENDC

def main():

    branch_opt = ""

    if "--all" in sys.argv:
        branch_opt = "--all"

    pr = subprocess.Popen(["/usr/bin/curl '{0}' --compressed".format(TRELLO_URL)],
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE,
        shell=True
    )

    (out, error) = pr.communicate()

    trello_dict = {}

    for t in json.loads(out):
        labels = []
        for label in json.loads(json.dumps(t['labels'])):
            labels.append(bcolors.set_ansi_color("[" + label['name'] + "]", label['color']))

        trello_dict[t['idShort']] = u"{0} {1}".format(' '.join(labels), t['name'])

    pr = subprocess.Popen(['git branch -v {0}'.format(branch_opt)],
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE, 
        shell=True)

    (out, error) = pr.communicate()
    branches = out.rstrip().split('\n')

    for b in branches:
        is_current_branch = b[:2].strip()
        branch_infos = b[2:].split()
        branch_name = branch_infos[0]
        branch_head = branch_infos[1]
        branch_comment = ' '.join(branch_infos[2:])
        trello_card_name = ''

        if branch_name.count('-') == 1:
            trello_board_name, trello_card_no = branch_name.split('-')
            trello_card_name = trello_dict.get(int(trello_card_no),'')

        if is_current_branch == '*':
            branch_name = bcolors.set_ansi_color(branch_name,'green')
        else:
            branch_name = bcolors.set_ansi_color(branch_name,'red')

        branch_head = bcolors.set_ansi_color(branch_head,'yellow')

        if len(branch_name) > 16:
            print "%2s %-40s %-18s %s" % (
                is_current_branch,
                branch_name,
                branch_head,
                trello_card_name or branch_comment
            )
        else:
            print "%2s %-18s %-18s %s" % (
                is_current_branch,
                branch_name,
                branch_head,
                trello_card_name or branch_comment
            )

if __name__ == '__main__':
    main()