import os
import jinja2
import m2r2

from binarycpython.utils.functions import call_binary_c_config

from git import Repo

def generate_browser_url(ssh_url, branch=None):
    """
    Function to generate the browser url for a git repo
    """

    base = ssh_url.split('@')[-1].replace('.git', '').replace(':','/').strip()

    if not branch:
        return 'https://{}'.format(base)
    else:
        return 'https://{}/-/tree/{}'.format(base, branch)

def write_custom_footer():
    """
    Function to write the custom footer to the template file
    """

    TARGET_DIR = './_templates'

    output_text = """
{{% extends '!footer.html' %}}

{{%- block extrafooter %}}
<br><br>
Generated on binarycpython git branch: {binarycpython_git_branch} git revision {binarycpython_git_revision} url: <a href="{binarycpython_git_url}">git url</a>.
<br><br>
Using binary_c with bit branch {binary_c_git_branch}: git revision: {binary_c_git_revision} url: <a href="{binary_c_git_url}">git url</a>.

{{% endblock %}}
"""

    binary_c_git_branch = call_binary_c_config('git_branch').strip()
    binary_c_git_revision = call_binary_c_config('git_revision').strip()
    binary_c_git_url = generate_browser_url(call_binary_c_config('git_url').strip(), binary_c_git_branch)

    # for binarycpython git
    base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    local_repo = Repo(path=base_dir)

    binarycpython_git_branch = local_repo.active_branch.name
    binarycpython_git_revision = local_repo.active_branch.commit
    binarycpython_git_url = generate_browser_url(local_repo.remotes.origin.url, binarycpython_git_branch)

    formatted_text = output_text.format(
            binarycpython_git_branch=binarycpython_git_branch,
            binarycpython_git_revision=binarycpython_git_revision,
            binarycpython_git_url=binarycpython_git_url,

            binary_c_git_branch=binary_c_git_branch,
            binary_c_git_revision=binary_c_git_revision,
            binary_c_git_url=binary_c_git_url,
        ).strip()

    # Write to file
    with open("_templates/footer.html", 'w') as outfile_filehandle:
        outfile_filehandle.write(formatted_text)