import argparse
import os

from .git import Git
from .page_factory import PageFactory

def parse_args():
    parser = argparse.ArgumentParser(
        prog='g2h',
        description='Convert a git repository into markdown files Hugo can understand.')
    # TODO: Defaults for these two values should be $PWD.
    parser.add_argument('repo_path', help='Path to the root of git repository')
    parser.add_argument('out_dir', help='Path to where the generated files should be stored')
    parser.add_argument('--name', help='Name of the project. Default: directory name of repo')
    parser.add_argument('--content-subdir', help='Subdir(s) where the page will be served from. Default: None', default='')

    return parser.parse_args()

def main():
    args = parse_args()
    git = Git(args.repo_path)

    branches = sorted(git.get_branches(), key=lambda b: b.commit.committed_date, reverse=True)
    commits = git.get_commits()
    # TODO: Fix this for repo_path=(.|~)
    project_name = args.name if args.name is not None else os.path.basename(args.repo_path)
    tags = sorted(git.get_tags(), key=lambda t: t.commit.committed_date, reverse=True)

    factory = PageFactory(args.out_dir, project_name, args.content_subdir)
    factory.new_overview(branches, tags).render()
    factory.new_log(commits, branches, tags).render()
    for commit in commits:
        factory.new_commit(commit).render()

if __name__ == '__main__':
    main()
