# coding: utf-8
"""
This module contains commands to interact with satellite populator
and validator.

Commands included:

satellite-populate
--------

A command to populate the system based in an YAML file describing the
entities::

    $ satellite-populate file.yaml -h myhost.com -o /tmp/validation.yaml

validate
--------

A command to validate the system based in an validation file generated by
the populate or a YAML file with mode: validation::

    $ satellite-populate /tmp/validation.yaml

Use :code:`$ satellite-populate --help` for more info
"""
import sys

import click

from satellite_populate.main import populate


def execute_populate(datafile, verbose, output, mode, scheme, port, hostname,
                     username, password):
    """Populate using the data described in `datafile`:"""
    result = populate(
        datafile,
        verbose=verbose,
        output=output,
        mode=mode,
        scheme=scheme,
        port=port,
        hostname=hostname,
        username=username,
        password=password
    )

    result.logger.info(
        "{0} entities already existing in the system".format(
            len(result.found)
        )
    )

    if result.mode == 'populate':
        result.logger.info(
            "{0} entities were created in the system".format(
                len(result.created)
            )
        )

    if result.assertion_errors:
        for error in result.assertion_errors:
            data = error['data']
            result.logger.error(
                'assertion: %s is NOT %s to %s',
                data['value'], error['operator'], data['other']
            )
        if result.mode == 'validate':
            sys.exit("System entities did not validated!")

    if result.validation_errors:
        for error in result.validation_errors:
            result.logger.error(error['message'])
            result.logger.error(error['search'])
        if result.mode == 'validate':
            sys.exit("System entities did not validated!")
    else:
        if result.mode == 'validate':
            result.logger.info("System Validated!!!")


VERBOSE_HELP = """
envvar:POPULATE_VERBOSE
-v(1):DEBUG
-vv(2):INFO
-vvv(3):WARNING
-vvvv(4):ERROR
-vvvvv(5):CRITICAL
"""


@click.command()
@click.argument(
    'datafile',
    required=True,
    type=click.Path(),
    envvar='POPULATE_DATAFILE'
)
@click.option(
    '-v', '--verbose',
    count=True,
    envvar='POPULATE_VERBOSE',
    help=VERBOSE_HELP
)
@click.option(
    '-o', '--output',
    type=click.Path(),
    default=None,
    envvar='POPULATE_OUTPUT',
    help="""envvar:POPULATE_OUTPUT
    Filepath to output the validation file e.g: -o=validation_123.yaml
    """
)
@click.option(
    '-m', '--mode',
    type=click.Choice(choices=('populate', 'validate')),
    default=None,
    envvar='POPULATE_MODE',
    help="""envvar:POPULATE_MODE
    valid modes are populate and validate"""
)
@click.option('--scheme', default=None, envvar='POPULATE_SCHEMA',
              help="""envvar:POPULATE_SCHEMA\noptional url schema""")
@click.option('--port', default=None, envvar='POPULATE_PORT', type=int,
              help="""envvar:POPULATE_PORT\noptional url port""")
@click.option('-h', '--hostname', default=None, envvar='POPULATE_HOSTNAME',
              help="""envvar:POPULATE_HOSTNAME\nSatellite URL:server.com""")
@click.option('-u', '--username', default=None, envvar='POPULATE_USERNAME',
              help="""envvar:POPULATE_USERNAME\nAdmin user""")
@click.option('-p', '--password', default=None, envvar='POPULATE_PASSWORD',
              help="""envvar:POPULATE_PASSWORD\nAdmin Password""")
def main(datafile, verbose, output, mode, scheme, port, hostname, username,
         password):
    """Populates or validates Satellite entities. Full documentation can be
    found on: https://satellite-populate.readthedocs.io\n
        $ satellite-populate test_data.yaml -vv\n
        $ satellite-populate test_data.yaml -vv --mode=validate\n
        $ satellite-populate test_data.yaml -vv -h myserver.com
    """
    execute_populate(datafile, verbose, output, mode, scheme, port,
                     hostname, username, password)


if __name__ == "__main__":
    main()
