import argparse
import logging
import os
import sys
import gitubuntu.build
from gitubuntu.cache import CACHE_PATH
import gitubuntu.git_repository

import pygit2

def parse_args(subparsers=None, base_subparsers=None):
    kwargs = dict(
        description="Generate the orig tarballs for a given source package",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    if base_subparsers:
        kwargs['parents'] = base_subparsers
    if subparsers:
        parser = subparsers.add_parser('export-orig', **kwargs)
        help_text = "export-orig - Extract orig tarballs",
        parser.set_defaults(func=cli_main)
    else:
        parser = argparse.ArgumentParser(**kwargs)
    parser.add_argument('--dl-cache', type=str,
        help=("Cache directory for downloads."),
        default=os.path.join(
            os.getcwd(),
            os.getenv('GIT_DIR', '.git'),
            CACHE_PATH
        ),
    )
    parser.add_argument(
        '--for-merge',
        action='store_true',
        help="Generate orig tarballs for an Ubuntu merge. Implies "
             "searching Debian for published versions first.",
    )
    parser.add_argument(
        '--no-pristine-tar',
        action='store_true',
        help="Do not use pristine-tar branches to generate orig "
            "tarballs. This can be necessary as we stabilize the pristine-tar "
            "data generation, particularly if multiple component tarballs are "
            "present.",

    )
    parser.add_argument(
        '--commit',
        type=str,
        help="Git commitish to export tarballs for.",
        default='HEAD',
    )
    if not subparsers:
        return parser.parse_args()
    return "export-orig - %s" % kwargs['description']

def main(
    repo,
    commitish,
    search_list,
):
    """main entry point for export-orig

    @param repo: a gitubuntu.git_repository.GitUbuntuRepository object
    @param commitish: string commitish to build
    @param search_list: list of OrigSearchListEntry namedtuples

    Returns the list of paths to exported files, if any.
    """
    try:
        repo.get_commitish(commitish)
    except:
        logging.error(
            "%s is not a defined object in this git repository.",
            commitish,
        )
        return []

    commit_hash = str(
        repo.get_commitish(commitish).peel(pygit2.Commit).id
    )

    try:
        return gitubuntu.build.fetch_orig(
            orig_search_list=search_list,
            changelog=gitubuntu.git_repository.Changelog.from_treeish(
                repo.raw_repo,
                repo.raw_repo.get(commit_hash),
            ),
        )
    except gitubuntu.build.NativenessMismatchError as e:
        logging.error("%s" % e)
        return []

def cli_main(args):
    repo = gitubuntu.git_repository.GitUbuntuRepository('.')

    try:
        repo.get_commitish(args.commit)
    except:
        logging.error(
            "%s is not a defined object in this git repository.",
            args.commit,
        )
        return 1

    orig_search_list = gitubuntu.build.derive_orig_search_list_from_args(
        repo,
        commitish=args.commit,
        for_merge=args.for_merge,
        no_pristine_tar=args.no_pristine_tar,
        dl_cache=args.dl_cache,
    )

    tarballs = main(repo, args.commit, orig_search_list)

    if len(tarballs) > 0:
        return 0
    else:
        return 1
