# 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: 20220618

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('desktops.desktops_root_group.command_name', 'desktops'), cls=CommandGroupWithAlias, help=cli_util.override('desktops.desktops_root_group.help', """Create and manage cloud-hosted desktops which can be accessed from a web browser or installed client."""), short_help=cli_util.override('desktops.desktops_root_group.short_help', """Secure Desktops API"""))
@cli_util.help_option_group
def desktops_root_group():
    pass


@click.command(cli_util.override('desktops.desktop_group.command_name', 'desktop'), cls=CommandGroupWithAlias, help="""Provides information about a desktop including name, state, id, configuration, owner, and time created.""")
@cli_util.help_option_group
def desktop_group():
    pass


@click.command(cli_util.override('desktops.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('desktops.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


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


@click.command(cli_util.override('desktops.desktop_pool_group.command_name', 'desktop-pool'), cls=CommandGroupWithAlias, help="""Provides information about a desktop pool including all configuration parameters.""")
@cli_util.help_option_group
def desktop_pool_group():
    pass


desktops_root_group.add_command(desktop_group)
desktops_root_group.add_command(work_request_error_group)
desktops_root_group.add_command(work_request_log_entry_group)
desktops_root_group.add_command(work_request_group)
desktops_root_group.add_command(desktop_pool_group)


@work_request_group.command(name=cli_util.override('desktops.cancel_work_request.command_name', 'cancel'), help=u"""Cancel work request with the given ID. \n[Command Reference](cancelWorkRequest)""")
@cli_util.option('--work-request-id', required=True, help=u"""The ID of the asynchronous request.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.confirm_delete_option
@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 cancel_work_request(ctx, from_json, work_request_id, if_match):

    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 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('desktops', 'desktop_service', ctx)
    result = client.cancel_work_request(
        work_request_id=work_request_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@desktop_pool_group.command(name=cli_util.override('desktops.change_desktop_pool_compartment.command_name', 'change-compartment'), help=u"""Moves a desktop pool into a different compartment within the same tenancy. You must provide the OCID of the desktop pool and the OCID of the compartment that you are moving the pool to. \n[Command Reference](changeDesktopPoolCompartment)""")
@cli_util.option('--desktop-pool-id', required=True, help=u"""The OCID of the desktop pool.""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment which will contain the desktop pool.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the 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 change_desktop_pool_compartment(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_pool_id, compartment_id, if_match):

    if isinstance(desktop_pool_id, six.string_types) and len(desktop_pool_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-pool-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('desktops', 'desktop_service', ctx)
    result = client.change_desktop_pool_compartment(
        desktop_pool_id=desktop_pool_id,
        change_desktop_pool_compartment_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_pool_group.command(name=cli_util.override('desktops.create_desktop_pool.command_name', 'create'), help=u"""Creates a desktop pool with the given configuration parameters. \n[Command Reference](createDesktopPool)""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment which will contain the desktop pool.""")
@cli_util.option('--display-name', required=True, help=u"""A user friendly display name. Avoid entering confidential information.""")
@cli_util.option('--maximum-size', required=True, type=click.INT, help=u"""The maximum number of desktops permitted in the desktop pool.""")
@cli_util.option('--standby-size', required=True, type=click.INT, help=u"""The maximum number of standby desktops available in the desktop pool.""")
@cli_util.option('--shape-name', required=True, help=u"""The shape of the desktop pool.""")
@cli_util.option('--is-storage-enabled', required=True, type=click.BOOL, help=u"""Indicates whether storage is enabled for the desktop pool.""")
@cli_util.option('--storage-size-in-gbs', required=True, type=click.INT, help=u"""The size in GBs of the storage for the desktop pool.""")
@cli_util.option('--storage-backup-policy-id', required=True, help=u"""The backup policy OCID of the storage.""")
@cli_util.option('--device-policy', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--availability-policy', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--image', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--network-configuration', required=True, type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--contact-details', required=True, help=u"""Contact information of the desktop pool administrator. Avoid entering confidential information.""")
@cli_util.option('--are-privileged-users', required=True, type=click.BOOL, help=u"""Indicates whether desktop pool users have administrative privileges on their desktop.""")
@cli_util.option('--availability-domain', required=True, help=u"""The availability domain of the desktop pool.""")
@cli_util.option('--description', help=u"""A user friendly description providing additional information about the resource. Avoid entering confidential information.""")
@cli_util.option('--shape-config', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--use-dedicated-vm-host', type=custom_types.CliCaseInsensitiveChoice(["TRUE", "FALSE", "AUTO"]), help=u"""Indicates whether the desktop pool uses dedicated virtual machine hosts.""")
@cli_util.option('--session-lifecycle-actions', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--time-start-scheduled', type=custom_types.CLI_DATETIME, help=u"""The start time of the desktop pool.""" + custom_types.CLI_DATETIME.VALID_DATETIME_CLI_HELP_MESSAGE)
@cli_util.option('--time-stop-scheduled', type=custom_types.CLI_DATETIME, help=u"""The stop time of the desktop pool.""" + custom_types.CLI_DATETIME.VALID_DATETIME_CLI_HELP_MESSAGE)
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + 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. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--nsg-ids', type=custom_types.CLI_COMPLEX_TYPE, help=u"""A list of network security groups for the private access.""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--private-access-details', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--boot-volume-size-in-gbs', type=click.INT, help=u"""The size in GBs of the boot volume for the desktop pool.""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'shape-config': {'module': 'desktops', 'class': 'CreateDesktopPoolShapeConfigDetails'}, 'device-policy': {'module': 'desktops', 'class': 'DesktopDevicePolicy'}, 'availability-policy': {'module': 'desktops', 'class': 'DesktopAvailabilityPolicy'}, 'image': {'module': 'desktops', 'class': 'DesktopImage'}, 'network-configuration': {'module': 'desktops', 'class': 'DesktopNetworkConfiguration'}, 'session-lifecycle-actions': {'module': 'desktops', 'class': 'CreateDesktopPoolDesktopSessionLifecycleActions'}, 'freeform-tags': {'module': 'desktops', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'desktops', 'class': 'dict(str, dict(str, object))'}, 'nsg-ids': {'module': 'desktops', 'class': 'list[string]'}, 'private-access-details': {'module': 'desktops', 'class': 'CreateDesktopPoolPrivateAccessDetails'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'shape-config': {'module': 'desktops', 'class': 'CreateDesktopPoolShapeConfigDetails'}, 'device-policy': {'module': 'desktops', 'class': 'DesktopDevicePolicy'}, 'availability-policy': {'module': 'desktops', 'class': 'DesktopAvailabilityPolicy'}, 'image': {'module': 'desktops', 'class': 'DesktopImage'}, 'network-configuration': {'module': 'desktops', 'class': 'DesktopNetworkConfiguration'}, 'session-lifecycle-actions': {'module': 'desktops', 'class': 'CreateDesktopPoolDesktopSessionLifecycleActions'}, 'freeform-tags': {'module': 'desktops', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'desktops', 'class': 'dict(str, dict(str, object))'}, 'nsg-ids': {'module': 'desktops', 'class': 'list[string]'}, 'private-access-details': {'module': 'desktops', 'class': 'CreateDesktopPoolPrivateAccessDetails'}}, output_type={'module': 'desktops', 'class': 'DesktopPool'})
@cli_util.wrap_exceptions
def create_desktop_pool(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, compartment_id, display_name, maximum_size, standby_size, shape_name, is_storage_enabled, storage_size_in_gbs, storage_backup_policy_id, device_policy, availability_policy, image, network_configuration, contact_details, are_privileged_users, availability_domain, description, shape_config, use_dedicated_vm_host, session_lifecycle_actions, time_start_scheduled, time_stop_scheduled, freeform_tags, defined_tags, nsg_ids, private_access_details, boot_volume_size_in_gbs):

    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['maximumSize'] = maximum_size
    _details['standbySize'] = standby_size
    _details['shapeName'] = shape_name
    _details['isStorageEnabled'] = is_storage_enabled
    _details['storageSizeInGBs'] = storage_size_in_gbs
    _details['storageBackupPolicyId'] = storage_backup_policy_id
    _details['devicePolicy'] = cli_util.parse_json_parameter("device_policy", device_policy)
    _details['availabilityPolicy'] = cli_util.parse_json_parameter("availability_policy", availability_policy)
    _details['image'] = cli_util.parse_json_parameter("image", image)
    _details['networkConfiguration'] = cli_util.parse_json_parameter("network_configuration", network_configuration)
    _details['contactDetails'] = contact_details
    _details['arePrivilegedUsers'] = are_privileged_users
    _details['availabilityDomain'] = availability_domain

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

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

    if use_dedicated_vm_host is not None:
        _details['useDedicatedVmHost'] = use_dedicated_vm_host

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

    if time_start_scheduled is not None:
        _details['timeStartScheduled'] = time_start_scheduled

    if time_stop_scheduled is not None:
        _details['timeStopScheduled'] = time_stop_scheduled

    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)

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

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

    if boot_volume_size_in_gbs is not None:
        _details['bootVolumeSizeInGBs'] = boot_volume_size_in_gbs

    client = cli_util.build_client('desktops', 'desktop_service', ctx)
    result = client.create_desktop_pool(
        create_desktop_pool_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_group.command(name=cli_util.override('desktops.delete_desktop.command_name', 'delete'), help=u"""Deletes the desktop with the specified OCID. The service terminates the associated compute instance. The end-user loses access to the desktop instance permanently. Any associated block volume becomes inactive but is not deleted. \n[Command Reference](deleteDesktop)""")
@cli_util.option('--desktop-id', required=True, help=u"""The OCID of the desktop.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.confirm_delete_option
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the 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_desktop(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_id, if_match):

    if isinstance(desktop_id, six.string_types) and len(desktop_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-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('desktops', 'desktop_service', ctx)
    result = client.delete_desktop(
        desktop_id=desktop_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Please retrieve the work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_pool_group.command(name=cli_util.override('desktops.delete_desktop_pool.command_name', 'delete'), help=u"""Deletes a desktop pool with the specified OCID. The service terminates all compute instances and users immediately lose access to their desktops. You can choose to preserve the block volumes associated with the pool. \n[Command Reference](deleteDesktopPool)""")
@cli_util.option('--desktop-pool-id', required=True, help=u"""The OCID of the desktop pool.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.option('--are-volumes-preserved', type=click.BOOL, help=u"""Whether the volumes are preserved when a desktop pool is deleted.""")
@cli_util.confirm_delete_option
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the 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_desktop_pool(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_pool_id, if_match, are_volumes_preserved):

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

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    if are_volumes_preserved is not None:
        kwargs['are_volumes_preserved'] = are_volumes_preserved
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('desktops', 'desktop_service', ctx)
    result = client.delete_desktop_pool(
        desktop_pool_id=desktop_pool_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Please retrieve the work request 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 work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_group.command(name=cli_util.override('desktops.get_desktop.command_name', 'get'), help=u"""Provides information about the desktop with the specified OCID. \n[Command Reference](getDesktop)""")
@cli_util.option('--desktop-id', required=True, help=u"""The OCID of the desktop.""")
@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': 'desktops', 'class': 'Desktop'})
@cli_util.wrap_exceptions
def get_desktop(ctx, from_json, desktop_id):

    if isinstance(desktop_id, six.string_types) and len(desktop_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-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('desktops', 'desktop_service', ctx)
    result = client.get_desktop(
        desktop_id=desktop_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@desktop_pool_group.command(name=cli_util.override('desktops.get_desktop_pool.command_name', 'get'), help=u"""Returns information about the desktop pool including all configuration parameters and the current state. \n[Command Reference](getDesktopPool)""")
@cli_util.option('--desktop-pool-id', required=True, help=u"""The OCID of the desktop pool.""")
@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': 'desktops', 'class': 'DesktopPool'})
@cli_util.wrap_exceptions
def get_desktop_pool(ctx, from_json, desktop_pool_id):

    if isinstance(desktop_pool_id, six.string_types) and len(desktop_pool_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-pool-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('desktops', 'desktop_service', ctx)
    result = client.get_desktop_pool(
        desktop_pool_id=desktop_pool_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@work_request_group.command(name=cli_util.override('desktops.get_work_request.command_name', 'get'), help=u"""Gets the status of the work request with the given ID. \n[Command Reference](getWorkRequest)""")
@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': 'desktops', 'class': 'WorkRequest'})
@cli_util.wrap_exceptions
def get_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('desktops', 'desktop_service', ctx)
    result = client.get_work_request(
        work_request_id=work_request_id,
        **kwargs
    )
    cli_util.render_response(result, ctx)


@desktop_pool_group.command(name=cli_util.override('desktops.list_desktop_pool_desktops.command_name', 'list-desktop-pool-desktops'), help=u"""Returns a list of desktops within a given desktop pool. You can limit the results to an availability domain, desktop name, or desktop state. You can limit the number of results returned, sort the results by time or name, and sort in ascending or descending order. \n[Command Reference](listDesktopPoolDesktops)""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment of the desktop pool.""")
@cli_util.option('--desktop-pool-id', required=True, help=u"""The OCID of the desktop pool.""")
@cli_util.option('--availability-domain', help=u"""The name of the availability domain.""")
@cli_util.option('--display-name', help=u"""A filter to return only results with the given displayName.""")
@cli_util.option('--id', help=u"""A filter to return only results with the given OCID.""")
@cli_util.option('--lifecycle-state', help=u"""A filter to return only results with the given lifecycleState.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of results to return.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""A field to sort by.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""A field to indicate the sort order.""")
@cli_util.option('--page', help=u"""For list pagination.""")
@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': 'desktops', 'class': 'DesktopPoolDesktopCollection'})
@cli_util.wrap_exceptions
def list_desktop_pool_desktops(ctx, from_json, all_pages, page_size, compartment_id, desktop_pool_id, availability_domain, display_name, id, lifecycle_state, limit, sort_by, sort_order, page):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')
    if sort_by and not availability_domain and not all_pages:
        raise click.UsageError('You must provide an --availability-domain when doing a --sort-by, unless you specify the --all parameter')

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

    kwargs = {}
    if availability_domain is not None:
        kwargs['availability_domain'] = availability_domain
    if display_name is not None:
        kwargs['display_name'] = display_name
    if id is not None:
        kwargs['id'] = id
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    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
    if page is not None:
        kwargs['page'] = page
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('desktops', 'desktop_service', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@desktop_pool_group.command(name=cli_util.override('desktops.list_desktop_pool_volumes.command_name', 'list-desktop-pool-volumes'), help=u"""Returns a list of volumes within the given desktop pool. You can limit the results to an availability domain, volume name, or volume state. You can limit the number of results returned, sort the results by time or name, and sort in ascending or descending order. \n[Command Reference](listDesktopPoolVolumes)""")
@cli_util.option('--desktop-pool-id', required=True, help=u"""The OCID of the desktop pool.""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment of the desktop pool.""")
@cli_util.option('--availability-domain', help=u"""The name of the availability domain.""")
@cli_util.option('--display-name', help=u"""A filter to return only results with the given displayName.""")
@cli_util.option('--id', help=u"""A filter to return only results with the given OCID.""")
@cli_util.option('--lifecycle-state', help=u"""A filter to return only results with the given lifecycleState.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of results to return.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""A field to sort by.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""A field to indicate the sort order.""")
@cli_util.option('--page', help=u"""For list pagination.""")
@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': 'desktops', 'class': 'DesktopPoolVolumeCollection'})
@cli_util.wrap_exceptions
def list_desktop_pool_volumes(ctx, from_json, all_pages, page_size, desktop_pool_id, compartment_id, availability_domain, display_name, id, lifecycle_state, limit, sort_by, sort_order, page):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')
    if sort_by and not availability_domain and not all_pages:
        raise click.UsageError('You must provide an --availability-domain when doing a --sort-by, unless you specify the --all parameter')

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

    kwargs = {}
    if availability_domain is not None:
        kwargs['availability_domain'] = availability_domain
    if display_name is not None:
        kwargs['display_name'] = display_name
    if id is not None:
        kwargs['id'] = id
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    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
    if page is not None:
        kwargs['page'] = page
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('desktops', 'desktop_service', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@desktop_pool_group.command(name=cli_util.override('desktops.list_desktop_pools.command_name', 'list'), help=u"""Returns a list of desktop pools within the given compartment. You can limit the results to an availability domain, pool name, or pool state. You can limit the number of results returned, sort the results by time or name, and sort in ascending or descending order. \n[Command Reference](listDesktopPools)""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment of the desktop pool.""")
@cli_util.option('--availability-domain', help=u"""The name of the availability domain.""")
@cli_util.option('--display-name', help=u"""A filter to return only results with the given displayName.""")
@cli_util.option('--id', help=u"""A filter to return only results with the given OCID.""")
@cli_util.option('--lifecycle-state', help=u"""A filter to return only results with the given lifecycleState.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of results to return.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""A field to sort by.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""A field to indicate the sort order.""")
@cli_util.option('--page', help=u"""For list pagination.""")
@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': 'desktops', 'class': 'DesktopPoolCollection'})
@cli_util.wrap_exceptions
def list_desktop_pools(ctx, from_json, all_pages, page_size, compartment_id, availability_domain, display_name, id, lifecycle_state, limit, sort_by, sort_order, page):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')
    if sort_by and not availability_domain and not all_pages:
        raise click.UsageError('You must provide an --availability-domain when doing a --sort-by, unless you specify the --all parameter')

    kwargs = {}
    if availability_domain is not None:
        kwargs['availability_domain'] = availability_domain
    if display_name is not None:
        kwargs['display_name'] = display_name
    if id is not None:
        kwargs['id'] = id
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    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
    if page is not None:
        kwargs['page'] = page
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('desktops', 'desktop_service', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@desktop_group.command(name=cli_util.override('desktops.list_desktops.command_name', 'list'), help=u"""Returns a list of desktops filtered by the specified parameters. You can limit the results to an availability domain, desktop name, desktop OCID, desktop state, pool OCID, or compartment OCID. You can limit the number of results returned, sort the results by time or name, and sort in ascending or descending order. \n[Command Reference](listDesktops)""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment of the desktop pool.""")
@cli_util.option('--availability-domain', help=u"""The name of the availability domain.""")
@cli_util.option('--display-name', help=u"""A filter to return only results with the given displayName.""")
@cli_util.option('--id', help=u"""A filter to return only results with the given OCID.""")
@cli_util.option('--lifecycle-state', help=u"""A filter to return only results with the given lifecycleState.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of results to return.""")
@cli_util.option('--sort-by', type=custom_types.CliCaseInsensitiveChoice(["TIMECREATED", "DISPLAYNAME"]), help=u"""A field to sort by.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""A field to indicate the sort order.""")
@cli_util.option('--page', help=u"""For list pagination.""")
@cli_util.option('--desktop-pool-id', help=u"""The OCID of the desktop pool.""")
@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': 'desktops', 'class': 'DesktopCollection'})
@cli_util.wrap_exceptions
def list_desktops(ctx, from_json, all_pages, page_size, compartment_id, availability_domain, display_name, id, lifecycle_state, limit, sort_by, sort_order, page, desktop_pool_id):

    if all_pages and limit:
        raise click.UsageError('If you provide the --all option you cannot provide the --limit option')
    if sort_by and not availability_domain and not all_pages:
        raise click.UsageError('You must provide an --availability-domain when doing a --sort-by, unless you specify the --all parameter')

    kwargs = {}
    if availability_domain is not None:
        kwargs['availability_domain'] = availability_domain
    if display_name is not None:
        kwargs['display_name'] = display_name
    if id is not None:
        kwargs['id'] = id
    if lifecycle_state is not None:
        kwargs['lifecycle_state'] = lifecycle_state
    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
    if page is not None:
        kwargs['page'] = page
    if desktop_pool_id is not None:
        kwargs['desktop_pool_id'] = desktop_pool_id
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('desktops', 'desktop_service', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@work_request_error_group.command(name=cli_util.override('desktops.list_work_request_errors.command_name', 'list'), help=u"""Return a (paginated) list of errors for a given work request. \n[Command Reference](listWorkRequestErrors)""")
@cli_util.option('--work-request-id', required=True, help=u"""The ID of the asynchronous request.""")
@cli_util.option('--page', help=u"""For list pagination.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of results to return.""")
@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('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""A field to indicate the sort order.""")
@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': 'desktops', 'class': 'WorkRequestErrorCollection'})
@cli_util.wrap_exceptions
def list_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('desktops', 'desktop_service', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

        result = cli_util.list_call_get_all_results(
            client.list_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_work_request_errors,
            limit,
            page_size,
            work_request_id=work_request_id,
            **kwargs
        )
    else:
        result = client.list_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('desktops.list_work_request_logs.command_name', 'list-work-request-logs'), help=u"""Return a (paginated) list of logs for a given work request. \n[Command Reference](listWorkRequestLogs)""")
@cli_util.option('--work-request-id', required=True, help=u"""The ID of the asynchronous request.""")
@cli_util.option('--page', help=u"""For list pagination.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of results to return.""")
@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('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""A field to indicate the sort order.""")
@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': 'desktops', 'class': 'WorkRequestLogEntryCollection'})
@cli_util.wrap_exceptions
def list_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('desktops', 'desktop_service', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

        result = cli_util.list_call_get_all_results(
            client.list_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_work_request_logs,
            limit,
            page_size,
            work_request_id=work_request_id,
            **kwargs
        )
    else:
        result = client.list_work_request_logs(
            work_request_id=work_request_id,
            **kwargs
        )
    cli_util.render_response(result, ctx)


@work_request_group.command(name=cli_util.override('desktops.list_work_requests.command_name', 'list'), help=u"""Lists the work requests in a compartment. \n[Command Reference](listWorkRequests)""")
@cli_util.option('--compartment-id', required=True, help=u"""The OCID of the compartment of the desktop pool.""")
@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", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), help=u"""A filter to return only resources their lifecycleState 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"""For list pagination.""")
@cli_util.option('--limit', type=click.INT, help=u"""The maximum number of results to return.""")
@cli_util.option('--sort-order', type=custom_types.CliCaseInsensitiveChoice(["ASC", "DESC"]), help=u"""A field to indicate the sort order.""")
@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': 'desktops', 'class': 'WorkRequestSummaryCollection'})
@cli_util.wrap_exceptions
def list_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 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('desktops', 'desktop_service', ctx)
    if all_pages:
        if page_size:
            kwargs['limit'] = page_size

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


@desktop_group.command(name=cli_util.override('desktops.start_desktop.command_name', 'start'), help=u"""Starts the desktop with the specified OCID. \n[Command Reference](startDesktop)""")
@cli_util.option('--desktop-id', required=True, help=u"""The OCID of the desktop.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the 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 start_desktop(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_id, if_match):

    if isinstance(desktop_id, six.string_types) and len(desktop_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-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('desktops', 'desktop_service', ctx)
    result = client.start_desktop(
        desktop_id=desktop_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_pool_group.command(name=cli_util.override('desktops.start_desktop_pool.command_name', 'start'), help=u"""Starts the desktop pool with the specified OCID. Once the pool is ACTIVE, users will have access to their desktops within the pool. \n[Command Reference](startDesktopPool)""")
@cli_util.option('--desktop-pool-id', required=True, help=u"""The OCID of the desktop pool.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the 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 start_desktop_pool(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_pool_id, if_match):

    if isinstance(desktop_pool_id, six.string_types) and len(desktop_pool_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-pool-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('desktops', 'desktop_service', ctx)
    result = client.start_desktop_pool(
        desktop_pool_id=desktop_pool_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_group.command(name=cli_util.override('desktops.stop_desktop.command_name', 'stop'), help=u"""Stops the desktop with the specified OCID. Stopping a desktop causes the end-user to lose access to their desktop instance until the desktop is restarted. \n[Command Reference](stopDesktop)""")
@cli_util.option('--desktop-id', required=True, help=u"""The OCID of the desktop.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.option('--is-soft-stop', type=click.BOOL, help=u"""Force a STOP(power off) of the desktop if set to false""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the 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 stop_desktop(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_id, if_match, is_soft_stop):

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

    kwargs = {}
    if if_match is not None:
        kwargs['if_match'] = if_match
    if is_soft_stop is not None:
        kwargs['is_soft_stop'] = is_soft_stop
    kwargs['opc_request_id'] = cli_util.use_or_generate_request_id(ctx.obj['request_id'])
    client = cli_util.build_client('desktops', 'desktop_service', ctx)
    result = client.stop_desktop(
        desktop_id=desktop_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_pool_group.command(name=cli_util.override('desktops.stop_desktop_pool.command_name', 'stop'), help=u"""Stops the desktop pool with the specified OCID. Users will lose access to their desktops until you explicitly start the pool again. \n[Command Reference](stopDesktopPool)""")
@cli_util.option('--desktop-pool-id', required=True, help=u"""The OCID of the desktop pool.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the 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 stop_desktop_pool(ctx, from_json, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_pool_id, if_match):

    if isinstance(desktop_pool_id, six.string_types) and len(desktop_pool_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-pool-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('desktops', 'desktop_service', ctx)
    result = client.stop_desktop_pool(
        desktop_pool_id=desktop_pool_id,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_group.command(name=cli_util.override('desktops.update_desktop.command_name', 'update'), help=u"""Modifies information about the desktop such as the name. \n[Command Reference](updateDesktop)""")
@cli_util.option('--desktop-id', required=True, help=u"""The OCID of the desktop.""")
@cli_util.option('--display-name', help=u"""A user friendly display name. Avoid entering confidential information.""")
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + 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. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True)
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'freeform-tags': {'module': 'desktops', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'desktops', '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={'freeform-tags': {'module': 'desktops', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'desktops', 'class': 'dict(str, dict(str, object))'}})
@cli_util.wrap_exceptions
def update_desktop(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_id, display_name, freeform_tags, defined_tags, if_match):

    if isinstance(desktop_id, six.string_types) and len(desktop_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-id cannot be whitespace or empty string')
    if not force:
        if freeform_tags or defined_tags:
            if not click.confirm("WARNING: Updates to 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 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('desktops', 'desktop_service', ctx)
    result = client.update_desktop(
        desktop_id=desktop_id,
        update_desktop_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)


@desktop_pool_group.command(name=cli_util.override('desktops.update_desktop_pool.command_name', 'update'), help=u"""Modifies the configuration of the desktop pool such as the availability, contact information, description, name, device policy, pool size, standby size, and start or stop time. \n[Command Reference](updateDesktopPool)""")
@cli_util.option('--desktop-pool-id', required=True, help=u"""The OCID of the desktop pool.""")
@cli_util.option('--display-name', help=u"""A user friendly display name. Avoid entering confidential information.""")
@cli_util.option('--description', help=u"""A user friendly description providing additional information about the resource. Avoid entering confidential information.""")
@cli_util.option('--maximum-size', type=click.INT, help=u"""The maximum number of desktops permitted in the desktop pool.""")
@cli_util.option('--standby-size', type=click.INT, help=u"""The maximum number of standby desktops available in the desktop pool.""")
@cli_util.option('--device-policy', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--availability-policy', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--contact-details', help=u"""Contact information of the desktop pool administrator. Avoid entering confidential information.""")
@cli_util.option('--time-start-scheduled', type=custom_types.CLI_DATETIME, help=u"""The start time of the desktop pool.""" + custom_types.CLI_DATETIME.VALID_DATETIME_CLI_HELP_MESSAGE)
@cli_util.option('--time-stop-scheduled', type=custom_types.CLI_DATETIME, help=u"""The stop time of the desktop pool.""" + custom_types.CLI_DATETIME.VALID_DATETIME_CLI_HELP_MESSAGE)
@cli_util.option('--freeform-tags', type=custom_types.CLI_COMPLEX_TYPE, help=u"""Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see [Resource Tags]. Example: `{\"Department\": \"Finance\"}`""" + 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. For more information, see [Resource Tags]. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--session-lifecycle-actions', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--image', type=custom_types.CLI_COMPLEX_TYPE, help=u"""""" + custom_types.cli_complex_type.COMPLEX_TYPE_HELP)
@cli_util.option('--boot-volume-size-in-gbs', type=click.INT, help=u"""The size in GBs of the boot volume for the desktop pool.""")
@cli_util.option('--if-match', help=u"""For optimistic concurrency control.""")
@cli_util.option('--force', help="""Perform update without prompting for confirmation.""", is_flag=True)
@cli_util.option('--wait-for-state', type=custom_types.CliCaseInsensitiveChoice(["ACCEPTED", "IN_PROGRESS", "WAITING", "FAILED", "SUCCEEDED", "CANCELING", "CANCELED"]), multiple=True, help="""This operation asynchronously creates, modifies or deletes a resource and uses a work request to track the progress of the operation. Specify this option to perform the action and then wait until the work request reaches a certain state. Multiple states can be specified, returning on the first state. For example, --wait-for-state ACCEPTED --wait-for-state CANCELED 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 work request to reach the 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 work request has reached the state defined by --wait-for-state. Defaults to 30 seconds.""")
@json_skeleton_utils.get_cli_json_input_option({'device-policy': {'module': 'desktops', 'class': 'DesktopDevicePolicy'}, 'availability-policy': {'module': 'desktops', 'class': 'DesktopAvailabilityPolicy'}, 'freeform-tags': {'module': 'desktops', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'desktops', 'class': 'dict(str, dict(str, object))'}, 'session-lifecycle-actions': {'module': 'desktops', 'class': 'UpdateDesktopPoolDesktopSessionLifecycleActions'}, 'image': {'module': 'desktops', 'class': 'UpdateDesktopImage'}})
@cli_util.help_option
@click.pass_context
@json_skeleton_utils.json_skeleton_generation_handler(input_params_to_complex_types={'device-policy': {'module': 'desktops', 'class': 'DesktopDevicePolicy'}, 'availability-policy': {'module': 'desktops', 'class': 'DesktopAvailabilityPolicy'}, 'freeform-tags': {'module': 'desktops', 'class': 'dict(str, string)'}, 'defined-tags': {'module': 'desktops', 'class': 'dict(str, dict(str, object))'}, 'session-lifecycle-actions': {'module': 'desktops', 'class': 'UpdateDesktopPoolDesktopSessionLifecycleActions'}, 'image': {'module': 'desktops', 'class': 'UpdateDesktopImage'}})
@cli_util.wrap_exceptions
def update_desktop_pool(ctx, from_json, force, wait_for_state, max_wait_seconds, wait_interval_seconds, desktop_pool_id, display_name, description, maximum_size, standby_size, device_policy, availability_policy, contact_details, time_start_scheduled, time_stop_scheduled, freeform_tags, defined_tags, session_lifecycle_actions, image, boot_volume_size_in_gbs, if_match):

    if isinstance(desktop_pool_id, six.string_types) and len(desktop_pool_id.strip()) == 0:
        raise click.UsageError('Parameter --desktop-pool-id cannot be whitespace or empty string')
    if not force:
        if device_policy or availability_policy or freeform_tags or defined_tags or session_lifecycle_actions or image:
            if not click.confirm("WARNING: Updates to device-policy and availability-policy and freeform-tags and defined-tags and session-lifecycle-actions and image 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 maximum_size is not None:
        _details['maximumSize'] = maximum_size

    if standby_size is not None:
        _details['standbySize'] = standby_size

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

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

    if contact_details is not None:
        _details['contactDetails'] = contact_details

    if time_start_scheduled is not None:
        _details['timeStartScheduled'] = time_start_scheduled

    if time_stop_scheduled is not None:
        _details['timeStopScheduled'] = time_stop_scheduled

    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)

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

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

    if boot_volume_size_in_gbs is not None:
        _details['bootVolumeSizeInGBs'] = boot_volume_size_in_gbs

    client = cli_util.build_client('desktops', 'desktop_service', ctx)
    result = client.update_desktop_pool(
        desktop_pool_id=desktop_pool_id,
        update_desktop_pool_details=_details,
        **kwargs
    )
    if wait_for_state:

        if hasattr(client, 'get_work_request') and callable(getattr(client, 'get_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
                if 'opc-work-request-id' not in result.headers:
                    click.echo('Encountered error while waiting for work request to enter the specified state. Outputting last known resource state')
                    cli_util.render_response(result, ctx)
                    return

                click.echo('Action completed. Waiting until the work request has entered state: {}'.format(wait_for_state), file=sys.stderr)
                result = oci.wait_until(client, client.get_work_request(result.headers['opc-work-request-id']), 'status', wait_for_state, **wait_period_kwargs)
            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 work request entered the specified state. Outputting last known resource state', file=sys.stderr)
                cli_util.render_response(result, ctx)
                sys.exit(2)
            except Exception:
                click.echo('Encountered error while waiting for work request 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 work request to enter the specified state', file=sys.stderr)
    cli_util.render_response(result, ctx)
