#!/usr/bin/env python
import argparse
import os
import configparser
from os.path import expanduser

from bitbucket.bitbucket_api import Bitbucket
from git.git_cli import Git

config_file = os.path.join(expanduser("~"), '.bitbucket-helper.config')


def read_config(force_update=False):
    config = configparser.ConfigParser()

    if not force_update and os.path.isfile(config_file):
        config.read(config_file)
    else:
        host = input("[Bitbucket server hostname]: ")
        user = input("[Bitbucket username]: ")
        pa_token = input(
            "[Personal access token (from manaage account)]: ")
        cwd = input("[Working directory (defaults to ~/bitbucket/)]: ")

        if not cwd:
            cwd = os.path.join(expanduser("~"), "bitbucket")

        clone_type = input("[Clone using http or ssh]: ")

        print("Writing config to " + config_file)
        config["bitbucket"] = {'host': host, 'user': user,
                               'token': pa_token, 'path': cwd, 'clone_type': clone_type}
        with open(config_file, 'w') as configfile:
            config.write(configfile)

    return config["bitbucket"]


def get_bitbucket_repos():
    config = read_config()
    clone_type = config["clone_type"]

    bitbucket = Bitbucket(config["host"], config["user"], config["token"])

    for repo in bitbucket.repos():
        project_key = repo['project']['key']
        clone_links = repo['links']['clone']
        clone_link = list(filter(lambda t: t['name'] == clone_type, clone_links))[
            0]['href']

        git = Git(config["path"])

        repo_path = git.local_repo_path(project_key, clone_link)

        if os.path.exists(repo_path):
            git.pull(repo_path)
            git.prune_local(repo_path)
        else:
            git.clone(project_key, clone_link)


def gitlog():
    config = read_config()

    git = Git(config['path'])
    git.log(args)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='bitbucket-helper')
    sub_parser = parser.add_subparsers(dest='subparser_name')

    parser_clone = sub_parser.add_parser('clone')

    parser_log = sub_parser.add_parser('log')
    parser_log.add_argument(
        '--after', help='<date> Show commits more recent than a specific date')
    parser_log.add_argument(
        '--from_tag', help='Show commits from this tag')
    parser_log.add_argument(
        '--to_tag', help='Show commit to this tag')

    args = parser.parse_args()
    if args.subparser_name == 'clone':
        get_bitbucket_repos()
    elif args.subparser_name == 'log':
        gitlog()
    else:
        parser.print_help()
