# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from azure.cli.core.aaz import *


@register_command(
    "netappfiles volume bucket update",
)
class Update(AAZCommand):
    """Update a bucket for a volume. A bucket allows additional services, such as AI services, connect to the volume data contained in those buckets.

    :example: Buckets_CreateOrUpdate
        az netappfiles volume bucket update --resource-group myRG --account-name account1 --pool-name pool1 --volume-name volume1 --bucket-name bucket1 --group-id 1000 --user-id 1001 --permissions ReadOnly --fqdn fullyqualified.domainname.com --certificate-object <REDACTED> --on-certificate-conflict-action Update
    """

    _aaz_info = {
        "version": "2026-01-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.netapp/netappaccounts/{}/capacitypools/{}/volumes/{}/buckets/{}", "2026-01-01"],
        ]
    }

    AZ_SUPPORT_NO_WAIT = True

    AZ_SUPPORT_GENERIC_UPDATE = True

    def _handler(self, command_args):
        super()._handler(command_args)
        return self.build_lro_poller(self._execute_operations, self._output)

    _args_schema = None

    @classmethod
    def _build_arguments_schema(cls, *args, **kwargs):
        if cls._args_schema is not None:
            return cls._args_schema
        cls._args_schema = super()._build_arguments_schema(*args, **kwargs)

        # define Arg Group ""

        _args_schema = cls._args_schema
        _args_schema.account_name = AAZStrArg(
            options=["-a", "--account-name"],
            help="The name of the NetApp account",
            required=True,
            id_part="name",
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,127}$",
            ),
        )
        _args_schema.bucket_name = AAZStrArg(
            options=["-n", "--name", "--bucket-name"],
            help="The name of the bucket",
            required=True,
            id_part="child_name_3",
            fmt=AAZStrArgFormat(
                pattern="^([a-z]|(\\d(?!\\d{0,2}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})))([a-z\\d]|(\\.(?!(\\.|-)))|(-(?!\\.))){1,61}[a-z\\d]$",
                max_length=63,
                min_length=3,
            ),
        )
        _args_schema.pool_name = AAZStrArg(
            options=["-p", "--pool-name"],
            help="The name of the capacity pool",
            required=True,
            id_part="child_name_1",
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9][a-zA-Z0-9\\-_]{0,63}$",
                max_length=64,
                min_length=1,
            ),
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.volume_name = AAZStrArg(
            options=["-v", "--volume-name"],
            help="The name of the volume",
            required=True,
            id_part="child_name_2",
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z][a-zA-Z0-9\\-_]{0,63}$",
                max_length=64,
                min_length=1,
            ),
        )

        # define Arg Group "CertificateAkvDetails"

        _args_schema = cls._args_schema
        _args_schema.certificate_key_vault_uri = AAZStrArg(
            options=["--cert-kv-uri", "--certificate-key-vault-uri"],
            arg_group="CertificateAkvDetails",
            help="The base URI of the Azure Key Vault that is used when retrieving the bucket certificate.",
            nullable=True,
        )
        _args_schema.certificate_name = AAZStrArg(
            options=["--certificate-name"],
            arg_group="CertificateAkvDetails",
            help="The name of the bucket server certificate stored in the Azure Key Vault.",
            nullable=True,
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9-]{1,127}$",
                max_length=127,
                min_length=1,
            ),
        )

        # define Arg Group "CifsUser"

        _args_schema = cls._args_schema
        _args_schema.username = AAZStrArg(
            options=["--username"],
            arg_group="CifsUser",
            help="The CIFS user's username",
            nullable=True,
        )

        # define Arg Group "CredentialsAkvDetails"

        _args_schema = cls._args_schema
        _args_schema.credentials_key_vault_uri = AAZStrArg(
            options=["--creds-kv-uri", "--credentials-key-vault-uri"],
            arg_group="CredentialsAkvDetails",
            help="The base URI of the Azure Key Vault that is used when storing the bucket credentials.",
            nullable=True,
        )
        _args_schema.secret_name = AAZStrArg(
            options=["--secret-name"],
            arg_group="CredentialsAkvDetails",
            help="The name of the secret stored in Azure Key Vault. The associated key pair has the following structure:  { \"access_key_id\": `\"<REDACTED>\"`, \"secret_access_key\": `\"<REDACTED>\"` }",
            nullable=True,
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9-]{1,127}$",
                max_length=127,
                min_length=1,
            ),
        )

        # define Arg Group "NfsUser"

        _args_schema = cls._args_schema
        _args_schema.group_id = AAZIntArg(
            options=["--group-id"],
            arg_group="NfsUser",
            help="The NFS user's GID",
            nullable=True,
        )
        _args_schema.user_id = AAZIntArg(
            options=["--user-id"],
            arg_group="NfsUser",
            help="The NFS user's UID",
            nullable=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.permissions = AAZStrArg(
            options=["--permissions"],
            arg_group="Properties",
            help="Access permissions for the bucket. Either ReadOnly or ReadWrite. The default is ReadOnly if no value is provided during bucket creation.",
            nullable=True,
            enum={"ReadOnly": "ReadOnly", "ReadWrite": "ReadWrite"},
        )

        # define Arg Group "Server"

        _args_schema = cls._args_schema
        _args_schema.certificate_object = AAZPasswordArg(
            options=["--certificate-object"],
            arg_group="Server",
            help="The base64-encoded contents of a PEM file, which includes both the bucket server's certificate and private key. It is generated by the end user and allows the user to access volume data in a read-only manner. Note: This is only used when Azure Key Vault is not configured. This property is mutually exclusive with the Azure Key Vault 'akv' properties.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=20480,
                min_length=1,
            ),
            blank=AAZPromptPasswordInput(
                msg="Password:",
            ),
        )
        _args_schema.fqdn = AAZStrArg(
            options=["--fqdn"],
            arg_group="Server",
            help="The host part of the bucket URL, resolving to the bucket IP address and allowed by the server certificate.",
            nullable=True,
        )
        _args_schema.on_certificate_conflict_action = AAZStrArg(
            options=["--cert-conflict-action", "--on-certificate-conflict-action"],
            arg_group="Server",
            help="Action to take when there is a certificate conflict. Possible values include: 'Update', 'Fail'",
            nullable=True,
            enum={"Fail": "Fail", "Update": "Update"},
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.BucketsGet(ctx=self.ctx)()
        self.pre_instance_update(self.ctx.vars.instance)
        self.InstanceUpdateByJson(ctx=self.ctx)()
        self.InstanceUpdateByGeneric(ctx=self.ctx)()
        self.post_instance_update(self.ctx.vars.instance)
        yield self.BucketsCreateOrUpdate(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    @register_callback
    def pre_instance_update(self, instance):
        pass

    @register_callback
    def post_instance_update(self, instance):
        pass

    def _output(self, *args, **kwargs):
        result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True)
        return result

    class BucketsGet(AAZHttpOperation):
        CLIENT_TYPE = "MgmtClient"

        def __call__(self, *args, **kwargs):
            request = self.make_request()
            session = self.client.send_request(request=request, stream=False, **kwargs)
            if session.http_response.status_code in [200]:
                return self.on_200(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/buckets/{bucketName}",
                **self.url_parameters
            )

        @property
        def method(self):
            return "GET"

        @property
        def error_format(self):
            return "MgmtErrorFormat"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "accountName", self.ctx.args.account_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "bucketName", self.ctx.args.bucket_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "poolName", self.ctx.args.pool_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
                **self.serialize_url_param(
                    "volumeName", self.ctx.args.volume_name,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2026-01-01",
                    required=True,
                ),
            }
            return parameters

        @property
        def header_parameters(self):
            parameters = {
                **self.serialize_header_param(
                    "Accept", "application/json",
                ),
            }
            return parameters

        def on_200(self, session):
            data = self.deserialize_http_content(session)
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_200
            )

        _schema_on_200 = None

        @classmethod
        def _build_schema_on_200(cls):
            if cls._schema_on_200 is not None:
                return cls._schema_on_200

            cls._schema_on_200 = AAZObjectType()
            _UpdateHelper._build_schema_bucket_read(cls._schema_on_200)

            return cls._schema_on_200

    class BucketsCreateOrUpdate(AAZHttpOperation):
        CLIENT_TYPE = "MgmtClient"

        def __call__(self, *args, **kwargs):
            request = self.make_request()
            session = self.client.send_request(request=request, stream=False, **kwargs)
            if session.http_response.status_code in [202]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_200_201,
                    self.on_error,
                    lro_options={"final-state-via": "azure-async-operation"},
                    path_format_arguments=self.url_parameters,
                )
            if session.http_response.status_code in [200, 201]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_200_201,
                    self.on_error,
                    lro_options={"final-state-via": "azure-async-operation"},
                    path_format_arguments=self.url_parameters,
                )

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/buckets/{bucketName}",
                **self.url_parameters
            )

        @property
        def method(self):
            return "PUT"

        @property
        def error_format(self):
            return "MgmtErrorFormat"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "accountName", self.ctx.args.account_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "bucketName", self.ctx.args.bucket_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "poolName", self.ctx.args.pool_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
                **self.serialize_url_param(
                    "volumeName", self.ctx.args.volume_name,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2026-01-01",
                    required=True,
                ),
            }
            return parameters

        @property
        def header_parameters(self):
            parameters = {
                **self.serialize_header_param(
                    "Content-Type", "application/json",
                ),
                **self.serialize_header_param(
                    "Accept", "application/json",
                ),
            }
            return parameters

        @property
        def content(self):
            _content_value, _builder = self.new_content_builder(
                self.ctx.args,
                value=self.ctx.vars.instance,
            )

            return self.serialize_content(_content_value)

        def on_200_201(self, session):
            data = self.deserialize_http_content(session)
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_200_201
            )

        _schema_on_200_201 = None

        @classmethod
        def _build_schema_on_200_201(cls):
            if cls._schema_on_200_201 is not None:
                return cls._schema_on_200_201

            cls._schema_on_200_201 = AAZObjectType()
            _UpdateHelper._build_schema_bucket_read(cls._schema_on_200_201)

            return cls._schema_on_200_201

    class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance(self.ctx.vars.instance)

        def _update_instance(self, instance):
            _instance_value, _builder = self.new_content_builder(
                self.ctx.args,
                value=instance,
                typ=AAZObjectType
            )
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("akvDetails", AAZObjectType)
                properties.set_prop("fileSystemUser", AAZObjectType)
                properties.set_prop("permissions", AAZStrType, ".permissions")
                properties.set_prop("server", AAZObjectType)

            akv_details = _builder.get(".properties.akvDetails")
            if akv_details is not None:
                akv_details.set_prop("certificateAkvDetails", AAZObjectType)
                akv_details.set_prop("credentialsAkvDetails", AAZObjectType)

            certificate_akv_details = _builder.get(".properties.akvDetails.certificateAkvDetails")
            if certificate_akv_details is not None:
                certificate_akv_details.set_prop("certificateKeyVaultUri", AAZStrType, ".certificate_key_vault_uri")
                certificate_akv_details.set_prop("certificateName", AAZStrType, ".certificate_name")

            credentials_akv_details = _builder.get(".properties.akvDetails.credentialsAkvDetails")
            if credentials_akv_details is not None:
                credentials_akv_details.set_prop("credentialsKeyVaultUri", AAZStrType, ".credentials_key_vault_uri")
                credentials_akv_details.set_prop("secretName", AAZStrType, ".secret_name")

            file_system_user = _builder.get(".properties.fileSystemUser")
            if file_system_user is not None:
                file_system_user.set_prop("cifsUser", AAZObjectType)
                file_system_user.set_prop("nfsUser", AAZObjectType)

            cifs_user = _builder.get(".properties.fileSystemUser.cifsUser")
            if cifs_user is not None:
                cifs_user.set_prop("username", AAZStrType, ".username")

            nfs_user = _builder.get(".properties.fileSystemUser.nfsUser")
            if nfs_user is not None:
                nfs_user.set_prop("groupId", AAZIntType, ".group_id")
                nfs_user.set_prop("userId", AAZIntType, ".user_id")

            server = _builder.get(".properties.server")
            if server is not None:
                server.set_prop("certificateObject", AAZStrType, ".certificate_object", typ_kwargs={"flags": {"secret": True}})
                server.set_prop("fqdn", AAZStrType, ".fqdn")
                server.set_prop("onCertificateConflictAction", AAZStrType, ".on_certificate_conflict_action")

            return _instance_value

    class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance_by_generic(
                self.ctx.vars.instance,
                self.ctx.generic_update_args
            )


class _UpdateHelper:
    """Helper class for Update"""

    _schema_bucket_read = None

    @classmethod
    def _build_schema_bucket_read(cls, _schema):
        if cls._schema_bucket_read is not None:
            _schema.id = cls._schema_bucket_read.id
            _schema.name = cls._schema_bucket_read.name
            _schema.properties = cls._schema_bucket_read.properties
            _schema.system_data = cls._schema_bucket_read.system_data
            _schema.type = cls._schema_bucket_read.type
            return

        cls._schema_bucket_read = _schema_bucket_read = AAZObjectType()

        bucket_read = _schema_bucket_read
        bucket_read.id = AAZStrType(
            flags={"read_only": True},
        )
        bucket_read.name = AAZStrType(
            flags={"read_only": True},
        )
        bucket_read.properties = AAZObjectType(
            flags={"client_flatten": True},
        )
        bucket_read.system_data = AAZObjectType(
            serialized_name="systemData",
            flags={"read_only": True},
        )
        bucket_read.type = AAZStrType(
            flags={"read_only": True},
        )

        properties = _schema_bucket_read.properties
        properties.akv_details = AAZObjectType(
            serialized_name="akvDetails",
        )
        properties.file_system_user = AAZObjectType(
            serialized_name="fileSystemUser",
        )
        properties.path = AAZStrType()
        properties.permissions = AAZStrType()
        properties.provisioning_state = AAZStrType(
            serialized_name="provisioningState",
            flags={"read_only": True},
        )
        properties.server = AAZObjectType()
        properties.status = AAZStrType(
            flags={"read_only": True},
        )

        akv_details = _schema_bucket_read.properties.akv_details
        akv_details.certificate_akv_details = AAZObjectType(
            serialized_name="certificateAkvDetails",
        )
        akv_details.credentials_akv_details = AAZObjectType(
            serialized_name="credentialsAkvDetails",
        )

        certificate_akv_details = _schema_bucket_read.properties.akv_details.certificate_akv_details
        certificate_akv_details.certificate_key_vault_uri = AAZStrType(
            serialized_name="certificateKeyVaultUri",
        )
        certificate_akv_details.certificate_name = AAZStrType(
            serialized_name="certificateName",
        )

        credentials_akv_details = _schema_bucket_read.properties.akv_details.credentials_akv_details
        credentials_akv_details.credentials_key_vault_uri = AAZStrType(
            serialized_name="credentialsKeyVaultUri",
        )
        credentials_akv_details.secret_name = AAZStrType(
            serialized_name="secretName",
        )

        file_system_user = _schema_bucket_read.properties.file_system_user
        file_system_user.cifs_user = AAZObjectType(
            serialized_name="cifsUser",
        )
        file_system_user.nfs_user = AAZObjectType(
            serialized_name="nfsUser",
        )

        cifs_user = _schema_bucket_read.properties.file_system_user.cifs_user
        cifs_user.username = AAZStrType()

        nfs_user = _schema_bucket_read.properties.file_system_user.nfs_user
        nfs_user.group_id = AAZIntType(
            serialized_name="groupId",
        )
        nfs_user.user_id = AAZIntType(
            serialized_name="userId",
        )

        server = _schema_bucket_read.properties.server
        server.certificate_common_name = AAZStrType(
            serialized_name="certificateCommonName",
            flags={"read_only": True},
        )
        server.certificate_expiry_date = AAZStrType(
            serialized_name="certificateExpiryDate",
            flags={"read_only": True},
        )
        server.fqdn = AAZStrType()
        server.ip_address = AAZStrType(
            serialized_name="ipAddress",
            flags={"read_only": True},
        )
        server.on_certificate_conflict_action = AAZStrType(
            serialized_name="onCertificateConflictAction",
        )

        system_data = _schema_bucket_read.system_data
        system_data.created_at = AAZStrType(
            serialized_name="createdAt",
        )
        system_data.created_by = AAZStrType(
            serialized_name="createdBy",
        )
        system_data.created_by_type = AAZStrType(
            serialized_name="createdByType",
        )
        system_data.last_modified_at = AAZStrType(
            serialized_name="lastModifiedAt",
        )
        system_data.last_modified_by = AAZStrType(
            serialized_name="lastModifiedBy",
        )
        system_data.last_modified_by_type = AAZStrType(
            serialized_name="lastModifiedByType",
        )

        _schema.id = cls._schema_bucket_read.id
        _schema.name = cls._schema_bucket_read.name
        _schema.properties = cls._schema_bucket_read.properties
        _schema.system_data = cls._schema_bucket_read.system_data
        _schema.type = cls._schema_bucket_read.type


__all__ = ["Update"]
