#!/usr/bin/env python
"""Script to unzip a .otreezip file from oTree Studio and apply our changes.

This is essentially a customised version of the ``otree unzip`` command to
streamline local development under git version control.

The ``.otreezip`` files downloaded from oTree Studio are actually tar-balls,
so we can use ``tar -zxvf name.otreezip`` or ``otree unzip name.otreezip`` for
this.

The script looks for the most recent file in ``~/Downloads/*-name.otreezip``
where ``name`` is taken from the current folder name and ``*`` is the random
three letter prefix from oTree Studio's download function.

After unzipping, applies some post-processing changes to use functionality not
available in oTree Studio:

* Setting ``DEMO_PAGE_TITLE`` and ``DEMO_PAGE_INTRO_HTML`` in ``settings.py``

Could go further:

* Adding ``POINTS_CUSTOM_NAME = 'tokens'`` to ``settings.py``
* Running black
* Replacing "from otree.api import *"
* Adding things to .gitignore (or reverting the oTree Studio changes there)
"""

import os
import subprocess
import sys


def run(cmd_string):
    print(cmd_string)
    subprocess.check_call(cmd_string, shell=True)


def main():
    project = os.path.split(os.path.abspath(os.path.curdir))[1]
    downloads = os.path.join(os.environ["HOME"], "Downloads")
    if not os.path.isdir(downloads):
        sys.exit(f"ERROR: Did not find directory {downloads}")
    inputs = [_ for _ in os.listdir(downloads) if _.endswith(f"-{project}.otreezip")]
    if not inputs:
        sys.exit(f"ERROR: No *-{project}.otreezip in downloads")
    if len(inputs) > 1:
        sys.stderr.write(
            f"More than one *-{project}.otreezip in downloads, taking latest\n"
        )
        inputs = sorted(
            inputs, key=lambda tar_ball: os.stat(f"{downloads}/{tar_ball}").st_ctime
        )
    tar_ball = inputs[-1]

    run(f"tar -zxvf {downloads}/{tar_ball}")
    # Cannot set DEMO_PAGE_TITLE in oTree Studio:
    run("""echo "DEMO_PAGE_TITLE = 'MDT project INTR-EXP-MET - oTree Demo'" >> settings.py""")
    # Cannot set DEMO_PAGE_INTRO_HTML in oTree Studio (must use triple quotes):
    run('''printf 'DEMO_PAGE_INTRO_HTML = """\nRisk attitude lottery game based on Holt and Laury (2002), followed by an interactive multi-player game about volunteering. <a href=\\\"https://github.com/peterjc/MDT-INTR-EXP-MET\\\">Source code on GitHub</a>.\n"""\n' >> settings.py''')
    # Cannot set custom session parameters in free oTree Studio:
    run("""sed -i.bak "s#name='farmer_framing', num_demo_participants=#name='farmer_framing', framing=0, num_demo_participants=#g" settings.py""")
    run("""sed -i.bak "s#name='community_centre_framing', num_demo_participants=#name='community_centre_framing', framing=1, num_demo_participants=#g" settings.py""")
    # run("""echo "POINTS_CUSTOM_NAME = 'tokens'" >> settings.py""")
    # run("black")
    print("----")
    print("Done")
    print("----")

if __name__ == "__main__":
    main()
