import glob
import subprocess

from setuptools import find_packages, setup


def sh(command):
    if isinstance(command, list):
        command = " ".join(command)
    return (
        subprocess.check_output(
            command,
            shell=True,
            stderr=subprocess.STDOUT,
        )
        .decode("utf-8")
        .rstrip()
    )


PACKAGE_NAME = "geoview"
VERSION = "0.0.1"

git_branch = sh("git rev-parse --abbrev-ref HEAD")
git_commit_hash = sh("git log -1 --format=%h")
git_commit_date = sh('git log -1 --date=format:"%Y/%m/%d %H:%M:%S" --format="%cd"')
git_commit_count = sh("git rev-list --count HEAD")
git_diff_name_only = sh("git diff --name-only")
if git_diff_name_only:
    git_diff_name_only = git_diff_name_only.replace("\n", ",")

doc_url = "https://pypi.org/project/geoview"
repo_url = "https://github.com/cubao/geoview"

# this is a hack, the easiest way I found to inject these metedata
with open(f"{PACKAGE_NAME}/__init__.py", "w") as f:
    f.write("# DO NOT EDIT THIS FILE, IT IS GENERATED BY SETUP.PY\n")
    f.write(f'__version__ = "{VERSION}"\n')
    f.write(f'package_name = "{PACKAGE_NAME}"\n')
    f.write(f'git_branch = "{git_branch}"\n')
    f.write(f'git_commit_hash = "{git_commit_hash}"\n')
    f.write(f'git_commit_date = "{git_commit_date}"\n')
    f.write(f"git_commit_count = {git_commit_count}\n")
    f.write(f'git_diff_name_only = "{git_diff_name_only}"\n')
    f.write(f'doc_url = "{doc_url}"\n')
    f.write(f'repo_url = "{repo_url}"\n')

with open("requirements.txt") as f:
    lines = f.readlines()
install_requires = [
    line.strip() for line in lines if line and not line.startswith("--")
]

data_export = [e[len("geoview/") :] for e in sorted(glob.glob("geoview/frontent/*"))]
setup(
    name=PACKAGE_NAME,
    version=VERSION,
    keywords=["geojson", "view"],
    description="geoview: view geojson data",
    url=doc_url,
    author="district10",
    author_email="dvorak4tzx@gmail.com",
    packages=find_packages(),
    platforms="any",
    zip_safe=False,
    include_package_data=True,
    package_data={
        f"{PACKAGE_NAME}": data_export,
    },
    install_requires=install_requires,
    python_requires=">=3.6",  # for those py35 or less users, please try f-string
)
