#!/usr/bin/env python

import requests
import oauthlib
from requests_oauthlib import OAuth1Session
import click
import pickle
import os
import sys
import yaml

from threading import Event
from http.server import BaseHTTPRequestHandler, HTTPServer, SimpleHTTPRequestHandler
import json
from pprint import pprint
from tabulate import tabulate
from bitbucket import BitBucketClient

def webhooks_in_table(webhooks):
    rows = []
    for webhook in webhooks:
        rows.append([
            "A" if webhook['active'] else "D",
            webhook['uuid'],
            webhook['description'],
            webhook['url'],
            ','.join(webhook['events'])
        ])
    print(tabulate(rows))

@click.group()
@click.option('--debug/--no-debug', default=False)
@click.option('--client-id', type = str, required = True, default=lambda: os.environ.get('BB_CLIENT_ID', ''), help = 'client key')
@click.option('--client-secret', type = str, required = True, default=lambda: os.environ.get('BB_CLIENT_SECRET', ''), help = 'client secret')
@click.pass_context
def cli(ctx, debug, client_id, client_secret):
    scope = ["webhook", "repository", "issue", "pullrequest"]

    ctx.obj['CLIENT_ID'] = client_id
    ctx.obj['CLIENT_SECRET'] = client_secret
    if os.path.exists(".access_token"):
        token = pickle.load(open(".access_token", 'rb'))
        bitbucket = BitBucketClient(client_id, client_secret=client_secret, token=token, scope=scope)
    else:
        bitbucket = BitBucketClient(client_id, client_secret=client_secret, scope=scope)
        pickle.dump(bitbucket.token, open(".access_token", 'wb'))
    # print(bitbucket.token)
    ctx.obj['bitbucket'] = bitbucket
    click.echo('Debug mode is %s' % ('on' if debug else 'off'))

@cli.group(chain=True)
@click.pass_context
def webhook(ctx):
    pass

@webhook.command('create')
@click.option('--user', type = str, required = True, default = 'linkernetworks', help = 'user name')
@click.option('--repo', type = str, required = True, help = 'repository name')
@click.option('--url', type = str, required = True, help = 'webhook url')
@click.option('--description', type = str, required = True, help = 'webhook description')
@click.option('--events', type = str, required = True, help = 'webhook events')
def webhook_create(ctx, user, repo, url, description, events = "repo:push"):
    bitbucket = ctx.obj['bitbucket']
    ret = bitbucket.create_hook(user, repo,
            url = url,
            description = description,
            events = events.split(","))
    print("Webhook is created %s" % (ret['uuid']))

@webhook.command('list')
@click.option('--user', type = str, required = True, default = 'linkernetworks', help = 'user name')
@click.option('--repo', type = str, required = True, help = 'repository name')
@click.option('--details', is_flag = True, help = 'show details')
@click.pass_context
def webhook_list(ctx, user, repo, details):
    print("Fetching Webhook list of %s/%s" % (user, repo))
    bitbucket = ctx.obj['bitbucket']
    webhooks = bitbucket.hooks(user, repo)
    if details:
        for webhook in webhooks:
            print(yaml.dump(webhook))
    else:
        webhooks_in_table(webhooks)

# cli = click.CommandCollection(sources=[cli1, cli2])
if __name__ == "__main__":
   cli(obj={})
