# --------------------------------------------------------------------------------------------
# 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(
    "connectedmachine install-patches",
)
class InstallPatches(AAZCommand):
    """Install patches on an Azure Arc-Enabled Server.

    :example: Sample command for install-patches
        az connectedmachine install-patches --resource-group MyResourceGroup --name MyMachine --maximum-duration PT4H --reboot-setting IfRequired --windows-parameters "{"classificationsToInclude": ["Critical", "Security"]}"
    """

    _aaz_info = {
        "version": "2022-12-27",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.hybridcompute/machines/{}/installpatches", "2022-12-27"],
        ]
    }

    AZ_SUPPORT_NO_WAIT = 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.name = AAZStrArg(
            options=["-n", "--name"],
            help="The name of the hybrid machine.",
            required=True,
            id_part="name",
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )

        # define Arg Group "InstallPatchesInput"

        _args_schema = cls._args_schema
        _args_schema.linux_parameters = AAZObjectArg(
            options=["--linux-parameters"],
            arg_group="InstallPatchesInput",
            help="Input for InstallPatches on a Linux VM, as directly received by the API",
        )
        _args_schema.maximum_duration = AAZStrArg(
            options=["--maximum-duration"],
            arg_group="InstallPatchesInput",
            help="Specifies the maximum amount of time that the operation will run. It must be an ISO 8601-compliant duration string such as PT4H (4 hours)",
            required=True,
        )
        _args_schema.reboot_setting = AAZStrArg(
            options=["--reboot-setting"],
            arg_group="InstallPatchesInput",
            help="Defines when it is acceptable to reboot a VM during a software update operation.",
            required=True,
            enum={"Always": "Always", "IfRequired": "IfRequired", "Never": "Never"},
        )
        _args_schema.windows_parameters = AAZObjectArg(
            options=["--windows-parameters"],
            arg_group="InstallPatchesInput",
            help="Input for InstallPatches on a Windows VM, as directly received by the API",
        )

        linux_parameters = cls._args_schema.linux_parameters
        linux_parameters.classifications_to_include = AAZListArg(
            options=["classifications-to-include"],
            help="The update classifications to select when installing patches for Linux.",
        )
        linux_parameters.package_name_masks_to_exclude = AAZListArg(
            options=["package-name-masks-to-exclude"],
            help="packages to exclude in the patch operation. Format: packageName_packageVersion",
        )
        linux_parameters.package_name_masks_to_include = AAZListArg(
            options=["package-name-masks-to-include"],
            help="packages to include in the patch operation. Format: packageName_packageVersion",
        )

        classifications_to_include = cls._args_schema.linux_parameters.classifications_to_include
        classifications_to_include.Element = AAZStrArg(
            enum={"Critical": "Critical", "Other": "Other", "Security": "Security"},
        )

        package_name_masks_to_exclude = cls._args_schema.linux_parameters.package_name_masks_to_exclude
        package_name_masks_to_exclude.Element = AAZStrArg()

        package_name_masks_to_include = cls._args_schema.linux_parameters.package_name_masks_to_include
        package_name_masks_to_include.Element = AAZStrArg()

        windows_parameters = cls._args_schema.windows_parameters
        windows_parameters.classifications_to_include = AAZListArg(
            options=["classifications-to-include"],
            help="The update classifications to select when installing patches for Windows.",
        )
        windows_parameters.exclude_kbs_requiring_reboot = AAZBoolArg(
            options=["exclude-kbs-requiring-reboot"],
            help="Filters out Kbs that don't have an InstallationRebootBehavior of 'NeverReboots' when this is set to true.",
        )
        windows_parameters.kb_numbers_to_exclude = AAZListArg(
            options=["kb-numbers-to-exclude"],
            help="Kbs to exclude in the patch operation",
        )
        windows_parameters.kb_numbers_to_include = AAZListArg(
            options=["kb-numbers-to-include"],
            help="Kbs to include in the patch operation",
        )
        windows_parameters.max_patch_publish_date = AAZDateTimeArg(
            options=["max-patch-publish-date"],
            help="This is used to install patches that were published on or before this given max published date.",
        )

        classifications_to_include = cls._args_schema.windows_parameters.classifications_to_include
        classifications_to_include.Element = AAZStrArg(
            enum={"Critical": "Critical", "Definition": "Definition", "FeaturePack": "FeaturePack", "Security": "Security", "ServicePack": "ServicePack", "Tools": "Tools", "UpdateRollUp": "UpdateRollUp", "Updates": "Updates"},
        )

        kb_numbers_to_exclude = cls._args_schema.windows_parameters.kb_numbers_to_exclude
        kb_numbers_to_exclude.Element = AAZStrArg()

        kb_numbers_to_include = cls._args_schema.windows_parameters.kb_numbers_to_include
        kb_numbers_to_include.Element = AAZStrArg()
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.MachinesInstallPatches(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

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

    class MachinesInstallPatches(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,
                    self.on_error,
                    lro_options={"final-state-via": "location"},
                    path_format_arguments=self.url_parameters,
                )
            if session.http_response.status_code in [200]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_200,
                    self.on_error,
                    lro_options={"final-state-via": "location"},
                    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.HybridCompute/machines/{name}/installPatches",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "name", self.ctx.args.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,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2022-12-27",
                    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,
                typ=AAZObjectType,
                typ_kwargs={"flags": {"required": True, "client_flatten": True}}
            )
            _builder.set_prop("linuxParameters", AAZObjectType, ".linux_parameters")
            _builder.set_prop("maximumDuration", AAZStrType, ".maximum_duration", typ_kwargs={"flags": {"required": True}})
            _builder.set_prop("rebootSetting", AAZStrType, ".reboot_setting", typ_kwargs={"flags": {"required": True}})
            _builder.set_prop("windowsParameters", AAZObjectType, ".windows_parameters")

            linux_parameters = _builder.get(".linuxParameters")
            if linux_parameters is not None:
                linux_parameters.set_prop("classificationsToInclude", AAZListType, ".classifications_to_include")
                linux_parameters.set_prop("packageNameMasksToExclude", AAZListType, ".package_name_masks_to_exclude")
                linux_parameters.set_prop("packageNameMasksToInclude", AAZListType, ".package_name_masks_to_include")

            classifications_to_include = _builder.get(".linuxParameters.classificationsToInclude")
            if classifications_to_include is not None:
                classifications_to_include.set_elements(AAZStrType, ".")

            package_name_masks_to_exclude = _builder.get(".linuxParameters.packageNameMasksToExclude")
            if package_name_masks_to_exclude is not None:
                package_name_masks_to_exclude.set_elements(AAZStrType, ".")

            package_name_masks_to_include = _builder.get(".linuxParameters.packageNameMasksToInclude")
            if package_name_masks_to_include is not None:
                package_name_masks_to_include.set_elements(AAZStrType, ".")

            windows_parameters = _builder.get(".windowsParameters")
            if windows_parameters is not None:
                windows_parameters.set_prop("classificationsToInclude", AAZListType, ".classifications_to_include")
                windows_parameters.set_prop("excludeKbsRequiringReboot", AAZBoolType, ".exclude_kbs_requiring_reboot")
                windows_parameters.set_prop("kbNumbersToExclude", AAZListType, ".kb_numbers_to_exclude")
                windows_parameters.set_prop("kbNumbersToInclude", AAZListType, ".kb_numbers_to_include")
                windows_parameters.set_prop("maxPatchPublishDate", AAZStrType, ".max_patch_publish_date")

            classifications_to_include = _builder.get(".windowsParameters.classificationsToInclude")
            if classifications_to_include is not None:
                classifications_to_include.set_elements(AAZStrType, ".")

            kb_numbers_to_exclude = _builder.get(".windowsParameters.kbNumbersToExclude")
            if kb_numbers_to_exclude is not None:
                kb_numbers_to_exclude.set_elements(AAZStrType, ".")

            kb_numbers_to_include = _builder.get(".windowsParameters.kbNumbersToInclude")
            if kb_numbers_to_include is not None:
                kb_numbers_to_include.set_elements(AAZStrType, ".")

            return self.serialize_content(_content_value)

        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()

            _schema_on_200 = cls._schema_on_200
            _schema_on_200.error_details = AAZObjectType(
                serialized_name="errorDetails",
            )
            _InstallPatchesHelper._build_schema_error_detail_read(_schema_on_200.error_details)
            _schema_on_200.excluded_patch_count = AAZIntType(
                serialized_name="excludedPatchCount",
                flags={"read_only": True},
            )
            _schema_on_200.failed_patch_count = AAZIntType(
                serialized_name="failedPatchCount",
                flags={"read_only": True},
            )
            _schema_on_200.installation_activity_id = AAZStrType(
                serialized_name="installationActivityId",
                flags={"read_only": True},
            )
            _schema_on_200.installed_patch_count = AAZIntType(
                serialized_name="installedPatchCount",
                flags={"read_only": True},
            )
            _schema_on_200.last_modified_date_time = AAZStrType(
                serialized_name="lastModifiedDateTime",
                flags={"read_only": True},
            )
            _schema_on_200.maintenance_window_exceeded = AAZBoolType(
                serialized_name="maintenanceWindowExceeded",
                flags={"read_only": True},
            )
            _schema_on_200.not_selected_patch_count = AAZIntType(
                serialized_name="notSelectedPatchCount",
                flags={"read_only": True},
            )
            _schema_on_200.os_type = AAZStrType(
                serialized_name="osType",
                flags={"read_only": True},
            )
            _schema_on_200.patch_service_used = AAZStrType(
                serialized_name="patchServiceUsed",
                flags={"read_only": True},
            )
            _schema_on_200.pending_patch_count = AAZIntType(
                serialized_name="pendingPatchCount",
                flags={"read_only": True},
            )
            _schema_on_200.reboot_status = AAZStrType(
                serialized_name="rebootStatus",
                flags={"read_only": True},
            )
            _schema_on_200.start_date_time = AAZStrType(
                serialized_name="startDateTime",
                flags={"read_only": True},
            )
            _schema_on_200.started_by = AAZStrType(
                serialized_name="startedBy",
                flags={"read_only": True},
            )
            _schema_on_200.status = AAZStrType(
                flags={"read_only": True},
            )

            return cls._schema_on_200


class _InstallPatchesHelper:
    """Helper class for InstallPatches"""

    _schema_error_detail_read = None

    @classmethod
    def _build_schema_error_detail_read(cls, _schema):
        if cls._schema_error_detail_read is not None:
            _schema.additional_info = cls._schema_error_detail_read.additional_info
            _schema.code = cls._schema_error_detail_read.code
            _schema.details = cls._schema_error_detail_read.details
            _schema.message = cls._schema_error_detail_read.message
            _schema.target = cls._schema_error_detail_read.target
            return

        cls._schema_error_detail_read = _schema_error_detail_read = AAZObjectType()

        error_detail_read = _schema_error_detail_read
        error_detail_read.additional_info = AAZListType(
            serialized_name="additionalInfo",
            flags={"read_only": True},
        )
        error_detail_read.code = AAZStrType(
            flags={"read_only": True},
        )
        error_detail_read.details = AAZListType(
            flags={"read_only": True},
        )
        error_detail_read.message = AAZStrType(
            flags={"read_only": True},
        )
        error_detail_read.target = AAZStrType(
            flags={"read_only": True},
        )

        additional_info = _schema_error_detail_read.additional_info
        additional_info.Element = AAZObjectType()

        _element = _schema_error_detail_read.additional_info.Element
        _element.type = AAZStrType(
            flags={"read_only": True},
        )

        details = _schema_error_detail_read.details
        details.Element = AAZObjectType()
        cls._build_schema_error_detail_read(details.Element)

        _schema.additional_info = cls._schema_error_detail_read.additional_info
        _schema.code = cls._schema_error_detail_read.code
        _schema.details = cls._schema_error_detail_read.details
        _schema.message = cls._schema_error_detail_read.message
        _schema.target = cls._schema_error_detail_read.target


__all__ = ["InstallPatches"]
