#!/usr/bin/env python

import json
import os
import sys
import subprocess

import yaml

try:
    import baker
except Exception as e:
    # TODO install baker and rerun
    print("baker not installed. pip install 'baker>=1.3,<2.0a0'")
    raise


os.environ['PYTHONPATH'] = os.getcwd()
#BAUBLE_DB_URL="postgresql://test:test@localhost/bauble" BAUBLE_ENV="development"

def load_env(name):
    filename = os.path.join(os.path.dirname(__file__), 'config.yaml')
    environ = yaml.load(open(filename))
    for key, value in environ[name].items():
        if isinstance(value, (int, float)):
            os.environ[key] = str(value)
        elif isinstance(value, (dict, list)):
            os.environ[key] = json.dumps(value)
        elif isinstance(value, bool):
            os.environ[key] = 'true' if value is True else 'false'
        elif value is None:
            # use None/null to unset the variable
            del os.environ[key]
        else:
            os.environ[key] = value
    return environ[name]


def shell(cmd, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):
    """
    Run a shell command.
    """
    try:
        return subprocess.check_call(cmd, stdin=stdin, stdout=stdout, stderr=stderr, shell=True)
    except subprocess.CalledProcessError as exc:
        print("** Error running command: {}".format(cmd))
        print(exc)
        sys.exit(exc.returncode)


@baker.command
def test(*args):
    """
    Run tests
    """
    load_env('test')
    pytest_args = ['py.test', 'test/spec'] if len(args) is 0 else ['py.test'] + list(args)
    shell(" ".join(pytest_args))


@baker.command
def virtualenv():
    # TODO: create the virtualenv and install the dependencies
    pass


@baker.command
def deploy():
    """
    Deploy to the production environment.
    """
    # TODO: copy to server and restart server
    pass


@baker.command
def clean():
    rm = lambda pattern: shell("find . -name {0} -type file | xargs -I {{}} rm -fr {{}}".format(pattern))
    rm("\*~")
    rm("\*.pyc")
    rm("__pycache__")


@baker.command(default=True)
def server(environment="local"):
    """
    Start the server
    """
    load_env(environment)
    print('Starting API server on {}...'.format(os.environ.get('API_BIND')))
    shell("gunicorn -c gunicorn.cfg bauble")


baker.run()
