#!/usr/bin/python
import sys

import click

USAGE = """\
Welcome to Pylero, the Python wrapper for the Polarion WSDL API. The Pylero
wrapper enables native python access to Polarion objects and functionality
using object oriented structure and functionality. This allows the developers to
use Pylero in a natural fashion without being concerned about the Polarion
details.

A configuration file must be filled out, which must be located either in the
current dir (the dir where the script is executed from) named **.pylero** or in
the user's home dir ~/.pylero

Default settings are stored in LIBDIR/pylero.cfg. This file should not
be modified, as it will be overwritten with any future updates.  Certificates
should be verified automatically, but if they aren't, you can add the path to
your CA to the cert_path config option.  These are the configurable values:

    [webservice]
    url=https://{your polarion web URL}/polarion
    svn_repo=https://{your polarion web URL}/repo
    user={your username}
    password={your password}
    default_project={your default project}
    #cert_path=/dir/with/certs
    #disable_manual_auth=False

If the password value is blank, it will prompt you for a password when you try
to access any of the pylero objects.

These can also be overridden with the following environment variables:
    POLARION_URL
    POLARION_REPO
    POLARION_USERNAME
    POLARION_PASSWORD
    POLARION_TIMEOUT
    POLARION_PROJECT
    POLARION_CERT_PATH
    POLARION_DISABLE_MANUAL_AUTH
"""

if len(sys.argv) == 2 and sys.argv[1] in ("-h", "--help"):
    print(USAGE)
    sys.exit(0)

from pylero.cli.cmd import CmdList
from pylero.cli.cmd import CmdUpdate


@click.group()
def cli():
    pass


@cli.command()
@click.option("-d", "--document", help="document with space e.g. 'space/document'")
@click.option("-e", "--query", help="query items e.g. --query='author.id:xhe'")
@click.option(
    "-D",
    "--is_document",
    default=False,
    is_flag=True,
    help="flag indicating that the action will reference a document",
)
@click.option("-i", "--testcase", help="testcase id")
@click.option(
    "-l",
    "--links",
    default=False,
    is_flag=True,
    help="flag indicating that the action will reference the links",
)
@click.option(
    "-m",
    "--template",
    default=False,
    is_flag=True,
    help="flag indicating that the action will reference a template",
)
@click.option("-p", "--plan_ids", help="plan ids in project")
@click.option("-q", "--requirement", help="requirement id")
@click.option("-r", "--run", help="test run")
@click.option(
    "-s",
    "--steps",
    default=False,
    is_flag=True,
    help="flag indicating that the action will reference the steps",
)
@click.option(
    "-t",
    "--workitem",
    default=False,
    is_flag=True,
    help="flag indicating that the action will reference workitem",
)
@click.option(
    "-w", "--wi_type", default="", help="type of workitem. e.g testcase, requirement"
)
def list(
    document,
    query,
    is_document,
    testcase,
    links,
    template,
    plan_ids,
    requirement,
    run,
    steps,
    workitem,
    wi_type=None,
):
    """list documents, testcases, steps of testcase, links of workitems, runs
    templates."""

    # instantiate the list object
    list_obj = CmdList()

    # get documents
    if is_document and query:
        docs = list_obj.list_documents_by_query(query)
        list_obj.print_documents(docs),

    # get workitems
    elif workitem:
        # workitems is from the document: 'space/document'
        if document:
            wis = list_obj.list_workitems_in_doc(document)
            list_obj.print_workitems(wis)
        # worktiems is from the query
        if query:
            wis = list_obj.list_workitems_by_query(query, wi_type)
            list_obj.print_workitems(wis)
        # get testcases is from run/template
        elif run:
            list_obj.print_testcases_from_run(run)

    # get links
    elif links:
        if testcase:
            list_obj.print_links_for_testcase(testcase)
        elif requirement:
            list_obj.print_links_for_requirement(requirement)

    # get templates by query
    elif query and template:
        list_obj.print_templates_by_query(query)

    # get runs by query
    elif query:
        list_obj.print_runs_by_query(query)

    # get steps for testcase
    elif steps and testcase:
        list_obj.print_steps_for_testcase(testcase)

    # get plan ids
    elif plan_ids:
        list_obj.print_plan_ids(plan_ids)

    else:
        click.echo("Please get usage: pylero-cmd list --help")


@cli.command()
@click.option("-a", "--assignee", default="None", help="assignee of run")
@click.option("-c", "--comment", help="verdict comment of testcase in run")
@click.option("-d", "--description", help="description of run")
@click.option("-e", "--query", help="query items e.g. --query=author.id:xhe")
@click.option(
    "-g",
    "--is_document",
    default=False,
    is_flag=True,
    help="flag indicating that the action will reference a document",
)
@click.option(
    "-p",
    "--doc_with_space",
    help="document id with space e.g --doc_with_space=KernelQE/DOC",
)
@click.option(
    "-b",
    "--doc_type",
    type=click.Choice(["generic", "testspecification", "requirementspecification"]),
    default="generic",
    help="document type, default='generic'",
)
@click.option(
    "-g",
    "--doc_wi_type",
    type=click.Choice(["testcase", "requirement"]),
    default="testcase",
    help="allowed workitem type in document, default='testcase'",
)
@click.option(
    "-f",
    "--doc_content",
    default="My sample document",
    help="HTML markup to document, default='My sample\
                    document'. It can be a html file e.g\
                    --doc_content=/home/xhe/plan.html",
)
@click.option("-D", "--debug", default=True, is_flag=True, help="debug mode")
@click.option("-i", "--testcase", help="testcase id")
@click.option("-m", "--template", help="run template")
@click.option("-p", "--plannedin", help="plannedin in run")
@click.option(
    "-o",
    "--result",
    type=click.Choice(["passed", "failed", "blocked"]),
    help="test result in run",
)
@click.option("-r", "--run", help="test run id")
@click.option(
    "-s",
    "--status",
    type=click.Choice(["notrun", "inprogress", "finished", "invalid"]),
    help="run status",
)
def update(
    assignee,
    comment,
    description,
    query,
    is_document,
    doc_with_space,
    doc_type,
    doc_wi_type,
    doc_content,
    debug,
    testcase,
    template,
    plannedin,
    result,
    run,
    status,
):
    """create run(s), update results and custom fileds for run(s)."""

    # instantiate the update object
    update_obj = CmdUpdate()

    if is_document:
        if not doc_with_space:
            print("Exit - Missing value of --doc_with_space")
            return False
        if "/" not in doc_with_space:
            print("Exit - 'SPACE/DOC_NAME' is required, --doc_with_space")
            return False

        # split string of doc_with_space
        doc_space_list = doc_with_space.split("/")
        space = doc_space_list[0]
        doc_name = doc_space_list[1]

        # set doc_title same as doc_name
        doc_title = doc_name

        # create document from string or html file
        update_obj.update_document(
            space, doc_name, doc_title, doc_wi_type, doc_type, "parent", doc_content
        )

    elif run:
        if result:
            if testcase:
                # update one case result for runs
                update_obj.update_1_case_result_for_run(
                    run, testcase, result, assignee, comment
                )
            else:
                # update all case results for runs
                update_obj.update_all_case_results_for_runs(
                    run, result, assignee, comment
                )
        else:
            # update/create runs
            update_obj.update_runs(
                run, template, plannedin, assignee, status, description
            )
    else:
        click.echo("Please get usage: pylero-cmd update --help")


if __name__ == "__main__":
    cli()
