# pyenv based tool for menhir
import logging

import menhir.tool as mtool
from menhir.tool_utils import OK, FAIL, NOTHING_TO_DO

log = logging.getLogger(__name__)


class Pyenv():
    pass


def tool():
    return Pyenv()


@mtool.name.register(Pyenv)
def name(arg):
    return "pyenv"


@mtool.is_using_tool.register(Pyenv)
def is_using_tool(tool, path):
    from os.path import exists, join
    path = join(path, 'requirements.txt')
    return exists(path)


@mtool.dependencies.register(Pyenv)
def dependencies(tool, path):
    return []


def run(cmd, *args, **kwargs):
    import subprocess
    res = subprocess.run(cmd, *args, **kwargs)
    if res.returncode:
        return False, FAIL
    return True, OK


@mtool.execute_build_phase.register(Pyenv)
def execute_build_phase(tool, path, phase_name):
    """Execute a build phase."""
    from os.path import basename
    import subprocess
    from menhir.tool_utils import package_script

    print('exec', path, phase_name)
    if phase_name == 'requirements':
        log.debug('pyenv requirements in %s', path)
        with package_script("/tools/pyenv/requirements.sh") as f:
            res = subprocess.run([f.name, path, basename(path)])

        if res.returncode:
            return FAIL
        return OK
    else:
        return NOTHING_TO_DO
