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.')
    parser.add_argument('--repo', help='Path to the root of git repository', default=os.getcwd())
    parser.add_argument('--out', help='Path to where the generated files should be stored', default=os.getcwd())
    # TODO: Add an actual default value.
    parser.add_argument('--name', help='Name of the project. Default: directory name of repo (TODO)')
    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)

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

    content_out = os.path.join(args.out, 'content', args.content_subdir)

    factory = PageFactory(content_out, project_name, args.content_subdir)
    factory.new_overview(branches, tags, head).render()
    factory.new_log(commits, branches, tags, head).render()
    for commit in commits:
        factory.new_commit(commit).render()
        tree = factory.new_tree(commit, '', git.get_repo())
        for tree_page in tree.build_pages(factory):
            tree_page.render()
            for file in tree_page.get_files():
                factory.new_file(commit, file).render()

if __name__ == '__main__':
    main()
