from invoke import run, task
import os


@task
def install(ctx):
    run('pip install -r requirements.txt')
    run('pip install -r requirements.test.txt')
    run('bundle')
    run('npm i')


@task
def test(ctx):
    run('nosetests')
    test_js_ci(ctx)


@task
def test_ci(ctx):
    run('nosetests --nologcapture --with-xunit --xunit-file $CIRCLE_TEST_REPORTS/nosetests.xml')
    test_js_ci(ctx)


def test_js_ci(ctx):
    run('./node_modules/.bin/karma start spec/javascripts/karma.config.js')


@task
def test_js(ctx):
    run('./node_modules/.bin/karma start spec/javascripts/karma.config.js')


@task
def update_version(ctx):
    run('echo "import os\n\n\ndef version():\n    if os.getenv(\'VERSION\'):\n        return os.getenv(\'VERSION\')\n    return \'$(git describe --tags)\'" > helix/constants/version.py')


@task
def serve(ctx):
    run('SP_DOCGEN_API_KEY=DC97-20AF-567E gunicorn -c gunicorn_config.py --pythonpath helix main:app')


@task
def update_heroku_version(ctx, environment):
    run('curl -n -X PATCH https://api.heroku.com/apps/sp-helix-%s/config-vars -d "{\\"VERSION\\": \\"$(git describe --tags)\\"}" -H "Content-Type: application/json" -H "Accept: application/vnd.heroku+json; version=3"' % environment)


@task
def db_migrate(ctx):
    run('PYTHONPATH=.:$PYTHONPATH alembic upgrade head')


@task
def serve_debug(ctx):
    run('PYTHONPATH=. FLASK_DEBUG=1 SP_DOCGEN_API_KEY=DC97-20AF-567E python helix/main.py')


@task
def db_diagram(ctx):
    db_uri = os.getenv('DATABASE_URL', 'postgres://pivotal:@localhost:5432/pivotal')
    run('eralchemy -i "{}" -o documentation/db_schema.png -x temp audit'.format(db_uri))

@task
def classes_diagrams(ctx):
    run('pyreverse -k -o calculators-diagram.png helix/calculators')
    run('pyreverse -k -o constants-diagram.png helix/constants')
    run('pyreverse -k -o forms-diagram.png helix/forms')
    run('pyreverse -k -o models-diagram.png helix/models')
    run('pyreverse -k -o validators-diagram.png helix/validators')
    run('rm -rf packages*.png ; mv classes.*-diagram.png documentation/')


@task
def serve_ssl(ctx):
    run('FLASK_DEBUG_SSL=true PORT=8443 PYTHONPATH=. FLASK_DEBUG=1 SP_DOCGEN_API_KEY=DC97-20AF-567E python helix/main.py')
