#!/usr/bin/env python
""" r-lint: Linting tool for R analysis container """

from __future__ import print_function

import click

import sys
import logging

import r_lint.lint
import r_lint.builder

@click.group()
@click.version_option(r_lint.__version__)
@click.option(
    '-v', '--verbose',
    is_flag = True,
    default = False,
    help = "Verbose output (print debug statements)"
)
def r_lint_cli(verbose):
    if verbose:
        logging.basicConfig(level=logging.DEBUG, format="\n%(levelname)s: %(message)s")
    else:
        logging.basicConfig(level=logging.INFO, format="\n%(levelname)s: %(message)s")

@r_lint_cli.command()
@click.argument(
    'pipeline_dir',
    type = click.Path(exists=True),
    required = True,
    metavar = "<R project directory>"
)
def lint(pipeline_dir):
    """ Check R project against linting guidelines """
    logging.info("Resolve R packages and extend conda environment...")
    lint_obj = r_lint.lint.RContainerLint(pipeline_dir)
    lint_obj.lint_rproject()
    lint_obj.print_results()

    if len(lint_obj.failed) > 0: sys.exit(1)

@r_lint_cli.command()
@click.argument(
    'rpackages',
    type = click.Path(exists=True),
    required = True,
    metavar = "<R package list>"
)
@click.argument(
    'conda_env',
    type = click.Path(exists=True),
    required = True,
    metavar = "<conda environment file>"
)
def build(rpackages, conda_env):
    """ Resolve R packages resources from Anaconda cloud """
    logging.info("Resolve R packages and extend conda environment...")
    env_builder = r_lint.builder.EnvBuilder(rpackages, conda_env)
    env_builder.build()
    env_builder.print_results()

    if len(env_builder.failed) > 0: sys.exit(1)


if __name__ == '__main__':
    print("""
 ______     __         __     __   __     ______  
/\  == \   /\ \       /\ \   /\ "-.\ \   /\__  _\ 
\ \  __<   \ \ \____  \ \ \  \ \ \-.  \  \/_/\ \/ 
 \ \_\ \_\  \ \_____\  \ \_\  \ \_\ \"\_\    \ \_\ 
  \/_/ /_/   \/_____/   \/_/   \/_/ \/_/     \/_/ 
                                                  
2018, QBiC software, Sven Fillinger
sven.fillinger@qbic.uni-tuebingen.de
    """)
    r_lint_cli()

