# coding: utf-8
# Copyright (c) 2016, 2026, Oracle and/or its affiliates.  All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
# NOTE: This class is auto generated by OracleSDKGenerator. DO NOT EDIT. API Version: 20230301

from __future__ import print_function
import click
import oci  # noqa: F401
import six  # noqa: F401
import sys  # noqa: F401
from oci_cli.cli_root import cli
from oci_cli import cli_constants  # noqa: F401
from oci_cli import cli_util
from oci_cli import json_skeleton_utils
from oci_cli import custom_types  # noqa: F401
from oci_cli.aliasing import CommandGroupWithAlias


@cli.command(cli_util.override('gdp.gdp_root_group.command_name', 'gdp'), cls=CommandGroupWithAlias, help=cli_util.override('gdp.gdp_root_group.help', """Use Guarded Data Pipelines to facilitate data transfer between different security domains. The service provides physical, network, and logistical isolation between security domains, malware and vulnerability scanning, auditing, and logging, with deep content inspection capabilities."""), short_help=cli_util.override('gdp.gdp_root_group.short_help', """Guarded Data Pipelines API"""))
@cli_util.help_option_group
def gdp_root_group():
    pass


@click.command(cli_util.override('gdp.gdp_work_request_group.command_name', 'gdp-work-request'), cls=CommandGroupWithAlias, help="""A description of work request status.""")
@cli_util.help_option_group
def gdp_work_request_group():
    pass


@click.command(cli_util.override('gdp.gdp_pipeline_group.command_name', 'gdp-pipeline'), cls=CommandGroupWithAlias, help="""Retrieves pipeline configuration information by identifier.""")
@cli_util.help_option_group
def gdp_pipeline_group():
    pass


@click.command(cli_util.override('gdp.work_request_error_group.command_name', 'work-request-error'), cls=CommandGroupWithAlias, help="""An error encountered while executing a work request.""")
@cli_util.help_option_group
def work_request_error_group():
    pass


@click.command(cli_util.override('gdp.work_request_log_entry_group.command_name', 'work-request-log-entry'), cls=CommandGroupWithAlias, help="""A log message from the execution of a work request.""")
@cli_util.help_option_group
def work_request_log_entry_group():
    pass


gdp_root_group.add_command(gdp_work_request_group)
gdp_root_group.add_command(gdp_pipeline_group)
gdp_root_group.add_command(work_request_error_group)
gdp_root_group.add_command(work_request_log_entry_group)


@gdp_pipeline_group.command(name=cli_util.override('gdp.change_gdp_pipeline_compartment.command_name', 'change-compartment'), help=u"""Moves a pipeline resource from one compartment to another. When provided, if-match is checked against etag values of the resource. \n[Command Reference](changeGdpPipelineCompartment)""")
@cli_util.option('--gdp-pipeline-id', required=True, help=u"""Unique pipeline identifier.""")
@cli_util.option('--compartment-id', required=True, help=u"""The [OCID] of the compartment into which the resource should be moved.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def change_gdp_pipeline_compartment(ctx, from_json, gdp_pipeline_id, compartment_id, if_match):

    if isinstance(gdp_pipeline_id, six.string_types) and len(gdp_pipeline_id.strip()) == 0:
        raise click.UsageError('Parameter --gdp-pipeline-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['compartmentId'] = compartment_id

    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.change_gdp_pipeline_compartment(
        gdp_pipeline_id=gdp_pipeline_id,
        change_gdp_pipeline_compartment_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.create_gdp_pipeline.command_name', 'create'), help=u"""Creates a new pipeline. \n[Command Reference](createGdpPipeline)""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment.""")
@cli_util.option('--display-name', required=True, help=u"""Pipeline short name.""")
@cli_util.option('--pipeline-type', required=True, help=u"""Type of pipeline. Can be SENDER or RECEIVER.""")
@cli_util.option('--bucket-details', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""Information about the bucket in the pipeline being configured.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--peering-region', required=True, help=u"""Public region name where the peered pipeline exists.""")
@cli_util.option('--description', help=u"""Short field input by customer for a description of the data pipeline use-case.""")
@cli_util.option('--service-log-group-id', help=u"""the OCID of the service log group.""")
@cli_util.option('--file-types', type=custom_types.CLI_COMPLEX_TYPE, help=u"""List of file types allowed to be transferred in the pipeline according to the authorization details (e.g. .pdf, .xml, .doc).""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--authorization-details', help=u"""Authorization information about the pipeline being configured.""")
@cli_util.option('--is-file-override-in-destination-enabled', type=click.BOOL, help=u"""Enable file override feature in destination bucket""")
@cli_util.option('--is-scanning-enabled', type=click.BOOL, help=u"""Determines whether GDP Scanning should be enabled for the pipeline.""")
@cli_util.option('--is-chunking-enabled', type=click.BOOL, help=u"""Determines whether file must be chunked during the transfer. This is only a property of SENDER pipelines.""")
@cli_util.option('--is-approval-needed', type=click.BOOL, help=u"""Determines whether file transfers need to go through an approval workflow.""")
@cli_util.option('--approval-key-vault-id', help=u"""The KMS vault OCID for the key to be used for file transfer approvals.""")
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. Example: `{\"bar-key\": \"value\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@json_skeleton_utils.get_cli_json_input_option({'file-types': {'module': 'gdp', 'class': 'list[string]'}, 'bucket-details': {'module': 'gdp', 'class': 'list[BucketDetailsDefinition]'}, 'freeform-tags': {'module': 'gdp', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'gdp', 'class': 'dict(str, dict(str, object))'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'file-types': {'module': 'gdp', 'class': 'list[string]'}, 'bucket-details': {'module': 'gdp', 'class': 'list[BucketDetailsDefinition]'}, 'freeform-tags': {'module': 'gdp', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'gdp', 'class': 'dict(str, dict(str, object))'}})
@cli_util.wrap_exceptions
def create_gdp_pipeline(ctx, from_json, compartment_id, display_name, pipeline_type, bucket_details, peering_region, description, service_log_group_id, file_types, authorization_details, is_file_override_in_destination_enabled, is_scanning_enabled, is_chunking_enabled, is_approval_needed, approval_key_vault_id, freeform_tags, defined_tags):

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['compartmentId'] = compartment_id
    _details['displayName'] = display_name
    _details['pipelineType'] = pipeline_type
    _details['bucketDetails'] = cli_util.parse_json_parameter("bucket_details", bucket_details)
    _details['peeringRegion'] = peering_region

    if description is not None:
        _details['description'] = description

    if service_log_group_id is not None:
        _details['serviceLogGroupId'] = service_log_group_id

    if file_types is not None:
        _details['fileTypes'] = cli_util.parse_json_parameter("file_types", file_types)

    if authorization_details is not None:
        _details['authorizationDetails'] = authorization_details

    if is_file_override_in_destination_enabled is not None:
        _details['isFileOverrideInDestinationEnabled'] = is_file_override_in_destination_enabled

    if is_scanning_enabled is not None:
        _details['isScanningEnabled'] = is_scanning_enabled

    if is_chunking_enabled is not None:
        _details['isChunkingEnabled'] = is_chunking_enabled

    if is_approval_needed is not None:
        _details['isApprovalNeeded'] = is_approval_needed

    if approval_key_vault_id is not None:
        _details['approvalKeyVaultId'] = approval_key_vault_id

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags)

    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.create_gdp_pipeline(
        create_gdp_pipeline_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.delete_gdp_pipeline.command_name', 'delete'), help=u"""Deletes a pipeline by identifier. \n[Command Reference](deleteGdpPipeline)""")
@cli_util.option('--gdp-pipeline-id', required=True, help=u"""Unique pipeline identifier.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@cli_util.confirm_delete_option
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "UPDATING", "ACTIVE", "INACTIVE", "DELETING", "DELETED", "FAILED", "NEEDS_ATTENTION"]), multiple=True, help="""This operation creates, modifies or deletes a resource that has a defined lifecycle state. Specify this option to perform the action and then wait until the resource reaches a given lifecycle state. Multiple states can be specified, returning on the first state. For example, --wait-for-state CREATING --wait-for-state NEEDS_ATTENTION would return on whichever lifecycle state is reached first. If timeout is reached, a return code of 2 is returned. For any other error, a return code of 1 is returned.""")
@cli_util.option('--max-wait-seconds', type=click.INT, help="""The maximum time to wait for the resource to reach the lifecycle state defined by --wait-for-state. Defaults to 1200 seconds.""")
@cli_util.option('--wait-interval-seconds', type=click.INT, help="""Check every --wait-interval-seconds to see whether the resource has reached the lifecycle state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def delete_gdp_pipeline(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, gdp_pipeline_id, if_match):

    if isinstance(gdp_pipeline_id, six.string_types) and len(gdp_pipeline_id.strip()) == 0:
        raise click.UsageError('Parameter --gdp-pipeline-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.delete_gdp_pipeline(
        gdp_pipeline_id=gdp_pipeline_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_gdp_work_request') and callable(getattr(client, 'get_gdp_work_request')):
            try:
                wait_period_kwargs = {}
                if max_wait_seconds is not None:
                    wait_period_kwargs['max_wait_seconds'] = max_wait_seconds
                if wait_interval_seconds is not None:
                    wait_period_kwargs['max_interval_seconds'] = wait_interval_seconds

                click.echo('Action completed. Waiting until the resource has entered state: {}'.format(wait_for_state), file=sys.stderr)
                oci.wait_until(client, client.get_gdp_work_request(gdp_pipeline_id), 'lifecycle_state', wait_for_state, succeed_on_not_found=True, **wait_period_kwargs)
            except oci.exceptions.ServiceError as e:
                # We make an initial service call so we can pass the result to oci.wait_until(), however if we are waiting on the
                # outcome of a delete operation it is possible that the resource is already gone and so the initial service call
                # will result in an exception that reflects a HTTP 404. In this case, we can exit with success (rather than raising
                # the exception) since this would have been the behaviour in the waiter anyway (as for delete we provide the argument
                # succeed_on_not_found=True to the waiter).
                #
                # Any non-404 should still result in the exception being thrown.
                if e.status == 404:
                    pass
                else:
                    raise
            except oci.exceptions.MaximumWaitTimeExceeded as e:
                # If we fail, we should show an error, but we should still provide the information to the customer
                click.echo('Failed to wait until the resource entered the specified state. Please retrieve the resource to find its current state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for resource to enter the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                raise
        else:
            click.echo('Unable to wait for the resource to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.get_gdp_pipeline.command_name', 'get'), help=u"""Retrieves a pipeline by identifier. \n[Command Reference](getGdpPipeline)""")
@cli_util.option('--gdp-pipeline-id', required=True, help=u"""Unique pipeline identifier.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'gdp', 'class': 'GdpPipeline'})
@cli_util.wrap_exceptions
def get_gdp_pipeline(ctx, from_json, gdp_pipeline_id):

    if isinstance(gdp_pipeline_id, six.string_types) and len(gdp_pipeline_id.strip()) == 0:
        raise click.UsageError('Parameter --gdp-pipeline-id cannot be whitespace or empty string')

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.get_gdp_pipeline(
        gdp_pipeline_id=gdp_pipeline_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@gdp_work_request_group.command(name=cli_util.override('gdp.get_gdp_work_request.command_name', 'get'), help=u"""Gets details of the work request with the given ID. \n[Command Reference](getGdpWorkRequest)""")
@cli_util.option('--work-request-id', required=True, help=u"""The ID of the asynchronous request.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'gdp', 'class': 'GdpWorkRequest'})
@cli_util.wrap_exceptions
def get_gdp_work_request(ctx, from_json, work_request_id):

    if isinstance(work_request_id, six.string_types) and len(work_request_id.strip()) == 0:
        raise click.UsageError('Parameter --work-request-id cannot be whitespace or empty string')

    kwargs = {}
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.get_gdp_work_request(
        work_request_id=work_request_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.list_gdp_pipelines.command_name', 'list'), help=u"""Returns a list of pipelines. \n[Command Reference](listGdpPipelines)""")
@cli_util.option('--compartment-id', help=u"""The ID of the compartment in which to list resources.""")
@cli_util.option('--display-name', help=u"""A filter to return only resources that match the entire display name given.""")
@cli_util.option('--gdp-pipeline-id', help=u"""Unique pipeline identifier.""")
@cli_util.option('--lifecycle-state', type=custom_types.CliCaseInsensitiveChoice(["CREATING", "UPDATING", "ACTIVE", "INACTIVE", "DELETING", "DELETED", "FAILED", "NEEDS_ATTENTION"]), help=u"""A filter to return only resources with a lifecycleState that matches the given lifecycleState.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of items to return.""")
@cli_util.option('--page', help=u"""A token representing the position at which to start retrieving results. This must come from the `opc-next-page` header field of a previous response.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either 'ASC' or 'DESC'.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["timeCreated", "displayName"]), help=u"""The field to sort by. Only one sort order may be provided. Default order for timeCreated is descending. Default order for displayName is ascending.""")
@cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""")
@cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'gdp', 'class': 'GdpPipelineCollection'})
@cli_util.wrap_exceptions
def list_gdp_pipelines(ctx, from_json, all_pages, page_size, compartment_id, display_name, gdp_pipeline_id, lifecycle_state, limit, page, sort_order, sort_by):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')

    kwargs = {}
    if compartment_id is not None:
        kwargs['compartment_id'] = compartment_id
    if display_name is not None:
        kwargs['display_name'] = display_name
    if gdp_pipeline_id is not None:
        kwargs['gdp_pipeline_id'] = gdp_pipeline_id
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    if limit is not None:
        kwargs['limit'] = limit
    if page is not None:
        kwargs['page'] = page
    if sort_order is not None:
        kwargs['sort_order'] = sort_order
    if sort_by is not None:
        kwargs['sort_by'] = sort_by
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

        result = cli_util.list_call_get_all_results(
            client.list_gdp_pipelines,
            **kwargs
        )
    elif limit is not None:
        result = cli_util.list_call_get_up_to_limit(
            client.list_gdp_pipelines,
            limit,
            page_size,
            **kwargs
        )
    else:
        result = client.list_gdp_pipelines(
            **kwargs
        )
    cli_util.render_response(result, ctx)


@work_request_error_group.command(name=cli_util.override('gdp.list_gdp_work_request_errors.command_name', 'list-gdp'), help=u"""Returns a (paginated) list of errors for the work request with the given ID. \n[Command Reference](listGdpWorkRequestErrors)""")
@cli_util.option('--work-request-id', required=True, help=u"""The ID of the asynchronous request.""")
@cli_util.option('--page', help=u"""A token representing the position at which to start retrieving results. This must come from the `opc-next-page` header field of a previous response.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of items to return.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["timestamp"]), help=u"""The field to sort by. Only one sort order may be provided. Default order for timestamp is descending.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either 'ASC' or 'DESC'.""")
@cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""")
@cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'gdp', 'class': 'WorkRequestErrorCollection'})
@cli_util.wrap_exceptions
def list_gdp_work_request_errors(ctx, from_json, all_pages, page_size, work_request_id, page, limit, sort_by, sort_order):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')

    if isinstance(work_request_id, six.string_types) and len(work_request_id.strip()) == 0:
        raise click.UsageError('Parameter --work-request-id cannot be whitespace or empty string')

    kwargs = {}
    if page is not None:
        kwargs['page'] = page
    if limit is not None:
        kwargs['limit'] = limit
    if sort_by is not None:
        kwargs['sort_by'] = sort_by
    if sort_order is not None:
        kwargs['sort_order'] = sort_order
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

        result = cli_util.list_call_get_all_results(
            client.list_gdp_work_request_errors,
            work_request_id=work_request_id,
            **kwargs
        )
    elif limit is not None:
        result = cli_util.list_call_get_up_to_limit(
            client.list_gdp_work_request_errors,
            limit,
            page_size,
            work_request_id=work_request_id,
            **kwargs
        )
    else:
        result = client.list_gdp_work_request_errors(
            work_request_id=work_request_id,
            **kwargs
        )
    cli_util.render_response(result, ctx)


@work_request_log_entry_group.command(name=cli_util.override('gdp.list_gdp_work_request_logs.command_name', 'list-gdp-work-request-logs'), help=u"""Returns a (paginated) list of logs for the work request with the given ID. \n[Command Reference](listGdpWorkRequestLogs)""")
@cli_util.option('--work-request-id', required=True, help=u"""The ID of the asynchronous request.""")
@cli_util.option('--page', help=u"""A token representing the position at which to start retrieving results. This must come from the `opc-next-page` header field of a previous response.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of items to return.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["timestamp"]), help=u"""The field to sort by. Only one sort order may be provided. Default order for timestamp is descending.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either 'ASC' or 'DESC'.""")
@cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""")
@cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'gdp', 'class': 'WorkRequestLogEntryCollection'})
@cli_util.wrap_exceptions
def list_gdp_work_request_logs(ctx, from_json, all_pages, page_size, work_request_id, page, limit, sort_by, sort_order):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')

    if isinstance(work_request_id, six.string_types) and len(work_request_id.strip()) == 0:
        raise click.UsageError('Parameter --work-request-id cannot be whitespace or empty string')

    kwargs = {}
    if page is not None:
        kwargs['page'] = page
    if limit is not None:
        kwargs['limit'] = limit
    if sort_by is not None:
        kwargs['sort_by'] = sort_by
    if sort_order is not None:
        kwargs['sort_order'] = sort_order
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

        result = cli_util.list_call_get_all_results(
            client.list_gdp_work_request_logs,
            work_request_id=work_request_id,
            **kwargs
        )
    elif limit is not None:
        result = cli_util.list_call_get_up_to_limit(
            client.list_gdp_work_request_logs,
            limit,
            page_size,
            work_request_id=work_request_id,
            **kwargs
        )
    else:
        result = client.list_gdp_work_request_logs(
            work_request_id=work_request_id,
            **kwargs
        )
    cli_util.render_response(result, ctx)


@gdp_work_request_group.command(name=cli_util.override('gdp.list_gdp_work_requests.command_name', 'list'), help=u"""Lists the work requests in a compartment. \n[Command Reference](listGdpWorkRequests)""")
@cli_util.option('--compartment-id', help=u"""The ID of the compartment in which to list resources.""")
@cli_util.option('--work-request-id', help=u"""The ID of the asynchronous work request.""")
@cli_util.option('--status', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "NEEDS_ATTENTION", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), help=u"""A filter to return only resources with a lifecycleState that matches the given OperationStatus.""")
@cli_util.option('--resource-id', help=u"""The ID of the resource affected by the work request.""")
@cli_util.option('--page', help=u"""A token representing the position at which to start retrieving results. This must come from the `opc-next-page` header field of a previous response.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of items to return.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""The sort order to use, either 'ASC' or 'DESC'.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["timeAccepted"]), help=u"""The field to sort by. Only one sort order may be provided. Default order for timeAccepted is descending.""")
@cli_util.option('--all', 'all_pages', is_flag=True, help="""Fetches all pages of results. If you provide this option, then you cannot provide the --limit option.""")
@cli_util.option('--page-size', type=click.INT, help="""When fetching results, the number of results to fetch per call. Only valid when used with --all or --limit, and ignored otherwise.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={}, output_type={'module': 'gdp', 'class': 'GdpWorkRequestSummaryCollection'})
@cli_util.wrap_exceptions
def list_gdp_work_requests(ctx, from_json, all_pages, page_size, compartment_id, work_request_id, status, resource_id, page, limit, sort_order, sort_by):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')

    kwargs = {}
    if compartment_id is not None:
        kwargs['compartment_id'] = compartment_id
    if work_request_id is not None:
        kwargs['work_request_id'] = work_request_id
    if status is not None:
        kwargs['status'] = status
    if resource_id is not None:
        kwargs['resource_id'] = resource_id
    if page is not None:
        kwargs['page'] = page
    if limit is not None:
        kwargs['limit'] = limit
    if sort_order is not None:
        kwargs['sort_order'] = sort_order
    if sort_by is not None:
        kwargs['sort_by'] = sort_by
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

        result = cli_util.list_call_get_all_results(
            client.list_gdp_work_requests,
            **kwargs
        )
    elif limit is not None:
        result = cli_util.list_call_get_up_to_limit(
            client.list_gdp_work_requests,
            limit,
            page_size,
            **kwargs
        )
    else:
        result = client.list_gdp_work_requests(
            **kwargs
        )
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.peer_gdp_pipeline.command_name', 'peer'), help=u"""Peers the pipeline. \n[Command Reference](peerGdpPipeline)""")
@cli_util.option('--peering-gdp-pipeline-id', required=True, help=u"""OCID of the peering pipeline.""")
@cli_util.option('--gdp-pipeline-id', required=True, help=u"""Unique pipeline identifier.""")
@cli_util.option('--peer-validation-nonce', help=u"""Unique one-time-token generated to validate the identity of the sender and prevent the peer request from being tampered with.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def peer_gdp_pipeline(ctx, from_json, peering_gdp_pipeline_id, gdp_pipeline_id, peer_validation_nonce, if_match):

    if isinstance(gdp_pipeline_id, six.string_types) and len(gdp_pipeline_id.strip()) == 0:
        raise click.UsageError('Parameter --gdp-pipeline-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}
    _details['peeringGdpPipelineId'] = peering_gdp_pipeline_id

    if peer_validation_nonce is not None:
        _details['peerValidationNonce'] = peer_validation_nonce

    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.peer_gdp_pipeline(
        gdp_pipeline_id=gdp_pipeline_id,
        peer_gdp_pipeline_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.rotate_gdp_pipeline_keys.command_name', 'rotate-gdp-pipeline-keys'), help=u"""Rotates the pipeline keys by resending the control message with a fresh pair of keys. \n[Command Reference](rotateGdpPipelineKeys)""")
@cli_util.option('--gdp-pipeline-id', required=True, help=u"""Unique pipeline identifier.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def rotate_gdp_pipeline_keys(ctx, from_json, gdp_pipeline_id, if_match):

    if isinstance(gdp_pipeline_id, six.string_types) and len(gdp_pipeline_id.strip()) == 0:
        raise click.UsageError('Parameter --gdp-pipeline-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.rotate_gdp_pipeline_keys(
        gdp_pipeline_id=gdp_pipeline_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.start_gdp_pipeline.command_name', 'start'), help=u"""Starts the pipeline. \n[Command Reference](startGdpPipeline)""")
@cli_util.option('--gdp-pipeline-id', required=True, help=u"""Unique pipeline identifier.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def start_gdp_pipeline(ctx, from_json, gdp_pipeline_id, if_match):

    if isinstance(gdp_pipeline_id, six.string_types) and len(gdp_pipeline_id.strip()) == 0:
        raise click.UsageError('Parameter --gdp-pipeline-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.start_gdp_pipeline(
        gdp_pipeline_id=gdp_pipeline_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.stop_gdp_pipeline.command_name', 'stop'), help=u"""Stops the pipeline. \n[Command Reference](stopGdpPipeline)""")
@cli_util.option('--gdp-pipeline-id', required=True, help=u"""Unique pipeline identifier.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@json_skeleton_utils.get_cli_json_input_option({})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={})
@cli_util.wrap_exceptions
def stop_gdp_pipeline(ctx, from_json, gdp_pipeline_id, if_match):

    if isinstance(gdp_pipeline_id, six.string_types) and len(gdp_pipeline_id.strip()) == 0:
        raise click.UsageError('Parameter --gdp-pipeline-id cannot be whitespace or empty string')

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.stop_gdp_pipeline(
        gdp_pipeline_id=gdp_pipeline_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@gdp_pipeline_group.command(name=cli_util.override('gdp.update_gdp_pipeline.command_name', 'update'), help=u"""Updates the pipeline. \n[Command Reference](updateGdpPipeline)""")
@cli_util.option('--gdp-pipeline-id', required=True, help=u"""Unique pipeline identifier.""")
@cli_util.option('--display-name', help=u"""Pipeline name. Can be renamed later.""")
@cli_util.option('--description', help=u"""Short field input by customer for a description of the data pipeline use-case.""")
@cli_util.option('--service-log-group-id', help=u"""the OCID of the service log group.""")
@cli_util.option('--file-types', type=custom_types.CLI_COMPLEX_TYPE, help=u"""List of file types allowed to be transferred in the data pipeline according to the authorization details (e.g. .pdf, .xml, .doc).""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--authorization-details', help=u"""Authorization information about the pipeline being configured.""")
@cli_util.option('--is-file-override-in-destination-enabled', type=click.BOOL, help=u"""Enable file override feature in destination bucket""")
@cli_util.option('--is-scanning-enabled', type=click.BOOL, help=u"""Determines whether GDP Scanning should be enabled for the pipeline.""")
@cli_util.option('--is-chunking-enabled', type=click.BOOL, help=u"""Determines whether file must be chunked during the transfer. This is only a property of SENDER pipelines.""")
@cli_util.option('--is-approval-needed', type=click.BOOL, help=u"""Determines whether file transfers need to go through an approval workflow.""")
@cli_util.option('--approval-key-vault-id', help=u"""The KMS vault OCID for the key to be used for file transfer approvals.""")
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. Example: `{\"bar-key\": \"value\"}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--defined-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Defined tags for this resource. Each key is predefined and scoped to a namespace. Example: `{\"foo-namespace\": {\"bar-key\": \"value\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--if-match', help=u"""For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.""")
@cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True)
@json_skeleton_utils.get_cli_json_input_option({'file-types': {'module': 'gdp', 'class': 'list[string]'}, 'freeform-tags': {'module': 'gdp', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'gdp', 'class': 'dict(str, dict(str, object))'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'file-types': {'module': 'gdp', 'class': 'list[string]'}, 'freeform-tags': {'module': 'gdp', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'gdp', 'class': 'dict(str, dict(str, object))'}})
@cli_util.wrap_exceptions
def update_gdp_pipeline(ctx, from_json, force, gdp_pipeline_id, display_name, description, service_log_group_id, file_types, authorization_details, is_file_override_in_destination_enabled, is_scanning_enabled, is_chunking_enabled, is_approval_needed, approval_key_vault_id, freeform_tags, defined_tags, if_match):

    if isinstance(gdp_pipeline_id, six.string_types) and len(gdp_pipeline_id.strip()) == 0:
        raise click.UsageError('Parameter --gdp-pipeline-id cannot be whitespace or empty string')
    if not force:
        if file_types or freeform_tags or defined_tags:
            if not click.confirm("WARNING: Updates to file-types and freeform-tags and defined-tags will replace any existing values. Are you sure you want to continue?"):
                ctx.abort()

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])

    _details = {}

    if display_name is not None:
        _details['displayName'] = display_name

    if description is not None:
        _details['description'] = description

    if service_log_group_id is not None:
        _details['serviceLogGroupId'] = service_log_group_id

    if file_types is not None:
        _details['fileTypes'] = cli_util.parse_json_parameter("file_types", file_types)

    if authorization_details is not None:
        _details['authorizationDetails'] = authorization_details

    if is_file_override_in_destination_enabled is not None:
        _details['isFileOverrideInDestinationEnabled'] = is_file_override_in_destination_enabled

    if is_scanning_enabled is not None:
        _details['isScanningEnabled'] = is_scanning_enabled

    if is_chunking_enabled is not None:
        _details['isChunkingEnabled'] = is_chunking_enabled

    if is_approval_needed is not None:
        _details['isApprovalNeeded'] = is_approval_needed

    if approval_key_vault_id is not None:
        _details['approvalKeyVaultId'] = approval_key_vault_id

    if freeform_tags is not None:
        _details['freeformTags'] = cli_util.parse_json_parameter("freeform_tags", freeform_tags)

    if defined_tags is not None:
        _details['definedTags'] = cli_util.parse_json_parameter("defined_tags", defined_tags)

    client = cli_util.build_client('gdp', 'guarded_data_pipeline', ctx)
    result = client.update_gdp_pipeline(
        gdp_pipeline_id=gdp_pipeline_id,
        update_gdp_pipeline_details=_details,
        **kwargs
    )
    cli_util.render_response(result, ctx)
