"""API methods for working with a single workflow."""
from cmem.cmempy import config
from cmem.cmempy.api import send_request


def get_workflow_uri():
    """Get endpoint URI pattern for a workflow."""
    return config.get_di_api_endpoint() + "/workflow/workflows/{}/{}"


def get_workflow_execute_uri():
    """Get execute URI pattern for a workflow."""
    return get_workflow_uri() + "/execute"


def get_workflow_status_uri():
    """Get status URI pattern for a workflow."""
    return get_workflow_uri() + "/status"


def get_workflow_execute_on_payload_uri():
    """Get execute on payload URI pattern for a workflow."""
    return get_workflow_uri() + "/executeOnPayload"


def get_workflow_editor_uri():
    """Get execute URI pattern for a workflow."""
    return config.get_di_api_endpoint() + "/workflow/editor/{}/{}"


def get_workflow(project_name, task_name):
    """GET retrieve single workflow."""
    return send_request(
        get_workflow_uri().format(project_name, task_name),
        method="GET"
    ).decode("utf-8")


def make_new_workflow(project_name, task_name, data=None):
    """PUT create workflow."""
    headers = {"Content-Type": "application/xml"}
    return send_request(
        get_workflow_uri().format(project_name, task_name),
        method="PUT",
        data=data,
        headers=headers
    ).decode("utf-8")


def execute_on_payload(project_name, task_name, data=None,
                       headers=None):
    """POST execute on payload."""
    if not headers:
        headers = {"Content-Type": "application/xml"}

    # pylint: disable-msg=duplicate-code
    return send_request(
        get_workflow_execute_on_payload_uri().format(project_name, task_name),
        method="POST",
        data=data,
        headers=headers
    ).decode("utf-8")


def delete_workflow(project_name, task_name):
    """DELETE remove workflow."""
    return send_request(
        get_workflow_uri().format(project_name, task_name),
        method="DELETE"
    ).decode("utf-8")


def execute_workflow(project_name, task_name):
    """PUT execute workflow."""
    return send_request(
        get_workflow_execute_uri().format(project_name, task_name),
        method="PUT"
    ).decode("utf-8")


def get_workflow_status(project_name, task_name):
    """GET workflow status.

    Returns gibberish, internal API endpoint
    use cmempy.workspace.activities.taskactivities.get_activity_status
    instead
    """
    return send_request(
        get_workflow_status_uri().format(project_name, task_name),
        method="GET"
    ).decode("utf-8")
