#!/usr/bin/env python

import os
import click
from x16cli import checks
from x16cli import actions
from x16cli import config as cfg

CWD = os.path.abspath(os.getcwd())


@click.group(help='X16 Command Line Interface v{}.'.format(cfg.VERSION))
def cli():
    pass


@cli.command(help='Create a new x16 asm project in the current folder.')
def init():
    try:
        actions.create_config_file(CWD)
        actions.create_folders(CWD)
        actions.clone_repos(CWD)
        actions.checkout_release(CWD)
        actions.compile_tools(CWD)
        actions.add_main_asm(CWD)
    except checks.ProjectPresentError:
        raise click.UsageError(
            'the current folder is already a x16cli project')
    except checks.RepositoryCloneError:
        raise click.UsageError(
            'something wrong happened downloading the needed tools')
    except checks.ReleaseNotFoundError:
        raise click.UsageError(
            'cannot checkout the release version, please check config again')


@cli.command(help='Build the project in a prg file with executable header.')
def build():
    actions.build(CWD)


@cli.command(help='X16 CLI application version.')
def version():
    click.echo(cfg.VERSION)


@cli.command(help='Build and run the project in the emulator.')
@click.option('-d', '--debug', is_flag=True, default=False, help='Run the emulator in debug mode.')
def run(debug):
    actions.build(CWD)
    actions.start_emu(CWD, debug)


if __name__ == "__main__":
    cli()
