# pre_publishing_hook.py generated by Pyrustic Manager
import os
import os.path
import sys
from pyrustic.jasonix import Jasonix


TEXT = """\
Install [Hubstore]({hubstore_link}):

```bash
$ pip install hubstore
```

or upgrade Hubstore:

```bash
$ pip install hubstore --upgrade --upgrade-strategy eager
```


Run Hubstore:

```bash
$ hubstore
```


Then paste or type `{owner}/{repo}` in Hubstore:

<br>

Enjoy !

<br><br>

Published with [Pyrustic]({pyrustic_link})
"""



def get_data():
    """
    Return None or a dict with the keys:
        'script', 'target', 'app_pkg' and 'version'
    """
    items = ("script", "target", "app_pkg", "version")
    data = None
    if len(sys.argv) == len(items):
        data = {item: sys.argv[i] for i, item in enumerate(items)}
    return data


def get_pyrustic_data_path(data):
    target = data["target"]
    app_pkg = data["app_pkg"]
    pyrustic_data_path = os.path.join(target, app_pkg,
                                      "pyrustic_data")
    if not os.path.exists(pyrustic_data_path):
        return None
    return pyrustic_data_path


def get_jasonix(pyrustic_data_path, config_name, readonly):
    if not pyrustic_data_path:
        return None
    config_path = os.path.join(pyrustic_data_path,
                               config_name)
    if not os.path.exists(config_path):
        return None
    jasonix = Jasonix(config_path, readonly=readonly)
    return jasonix


def get_release_description(owner, repo):
    hubstore_link = "https://github.com/pyrustic/hubstore"
    pyrustic_link = "https://github.com/pyrustic/pyrustic"

    text = TEXT.format(pyrustic_link=pyrustic_link,
                       hubstore_link=hubstore_link,
                       owner=owner, repo=repo)
    return text


def update_publishing_jasonix(target,
                              publishing_jasonix,
                              build_report_jasonix,
                              app_pkg, version):
    text = "Missing data in $APP_DIR/pyrustic_data/{}"
    if not build_report_jasonix.data:
        print(text.format("build_report.json"))
        return False
    if not publishing_jasonix.data:
        print(text.format("publishing.json"))
        return False
    # update owner
    if not publishing_jasonix.data["owner"]:
        owner = input("Github owner: ")
        print("")
        publishing_jasonix.data["owner"] = owner
    # update repo
    if not publishing_jasonix.data["repo"]:
        repo = os.path.basename(target)
        publishing_jasonix.data["repo"] = repo
    # update name
    if not publishing_jasonix.data["name"]:
        repo = publishing_jasonix.data["repo"]
        name = "{} v{}".format(repo, version)
        publishing_jasonix.data["name"] = name
    # update tag name
    tag_name = "v{}".format(version)
    publishing_jasonix.data["tag_name"] = tag_name
    # update target commitish
    if not publishing_jasonix.data["target_commitish"]:
        publishing_jasonix.data["target_commitish"] = "master"
    # update description
    owner = publishing_jasonix.data["owner"]
    repo = publishing_jasonix.data["repo"]
    description = get_release_description(owner, repo)
    publishing_jasonix.data["description"] = description
    # update prerelease
    if not publishing_jasonix.data["prerelease"]:
        publishing_jasonix.data["prerelease"] = False
    # update draft
    if not publishing_jasonix.data["draft"]:
        publishing_jasonix.data["draft"] = False
    # update asset path
    asset_path = build_report_jasonix.data["wheel_asset"]
    publishing_jasonix.data["asset_path"] = asset_path
    # update asset name
    asset_name = os.path.basename(asset_path)
    publishing_jasonix.data["asset_name"] = asset_name
    # update asset label
    if not publishing_jasonix.data["asset_label"]:
        publishing_jasonix.data["asset_label"] = "Download the Wheel"
    # save the changes
    publishing_jasonix.save()
    return True


def main():
    data = get_data()
    if not data:
        print("Missing sys.argv data")
        sys.exit(1)
    pyrustic_data_path = get_pyrustic_data_path(data)
    # get build_report jasonix
    build_report_jasonix = get_jasonix(pyrustic_data_path,
                                       "build_report.json", True)
    # get publishing jasonix
    publishing_jasonix = get_jasonix(pyrustic_data_path,
                                     "publishing.json", False)
    # update publishing.json
    if not update_publishing_jasonix(data["target"],
                                     publishing_jasonix,
                                     build_report_jasonix,
                                     data["app_pkg"],
                                     data["version"]):
        sys.exit(1)
    # exit
    sys.exit(0)


if __name__ == "__main__":
    main()
