# --------------------------------------------------------------------------------------------
# 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 *


class InstallPatches(AAZCommand):
    """Installs patches on the VM.

    :example: Install patches on a windows VM, allowing the maximum amount of time to be 4 hours, and the VM will reboot if required during the software update operation.
        az vm install-patches -g MyResourceGroup -n MyVm --maximum-duration PT4H --reboot-setting IfRequired --classifications-to-include-win Critical Security --exclude-kbs-requiring-reboot true

    :example: Install patches on a linux VM, allowing the maximum amount of time to be 4 hours, and the VM will reboot if required during the software update operation.
        az vm install-patches -g MyResourceGroup -n MyVm --maximum-duration PT4H --reboot-setting IfRequired --classifications-to-include-linux Critical
    """

    _aaz_info = {
        "version": "2024-11-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.compute/virtualmachines/{}/installpatches", "2024-11-01"],
        ]
    }

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

        # 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 = AAZDurationArg(
            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)",
        )
        _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.maintenance_run_id = AAZStrArg(
            options=["maintenance-run-id"],
            help="This is used as a maintenance run identifier for Auto VM Guest Patching in 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.",
            fmt=AAZDateTimeFormat(
                protocol="iso",
            ),
        )

        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.VirtualMachinesInstallPatches(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 VirtualMachinesInstallPatches(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.Compute/virtualMachines/{vmName}/installPatches",
                **self.url_parameters
            )

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

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

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

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2024-11-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,
                typ=AAZObjectType,
                typ_kwargs={"flags": {"required": True, "client_flatten": True}}
            )
            _builder.set_prop("linuxParameters", AAZObjectType, ".linux_parameters")
            _builder.set_prop("maximumDuration", AAZStrType, ".maximum_duration")
            _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("maintenanceRunId", AAZStrType, ".maintenance_run_id")
                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 = AAZObjectType(
                flags={"read_only": True},
            )
            _InstallPatchesHelper._build_schema_api_error_read(_schema_on_200.error)
            _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.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.patches = AAZListType(
                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.status = AAZStrType(
                flags={"read_only": True},
            )

            patches = cls._schema_on_200.patches
            patches.Element = AAZObjectType()

            _element = cls._schema_on_200.patches.Element
            _element.classifications = AAZListType(
                flags={"read_only": True},
            )
            _element.installation_state = AAZStrType(
                serialized_name="installationState",
                flags={"read_only": True},
            )
            _element.kb_id = AAZStrType(
                serialized_name="kbId",
                flags={"read_only": True},
            )
            _element.name = AAZStrType(
                flags={"read_only": True},
            )
            _element.patch_id = AAZStrType(
                serialized_name="patchId",
                flags={"read_only": True},
            )
            _element.version = AAZStrType(
                flags={"read_only": True},
            )

            classifications = cls._schema_on_200.patches.Element.classifications
            classifications.Element = AAZStrType()

            return cls._schema_on_200


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

    _schema_api_error_read = None

    @classmethod
    def _build_schema_api_error_read(cls, _schema):
        if cls._schema_api_error_read is not None:
            _schema.code = cls._schema_api_error_read.code
            _schema.details = cls._schema_api_error_read.details
            _schema.innererror = cls._schema_api_error_read.innererror
            _schema.message = cls._schema_api_error_read.message
            _schema.target = cls._schema_api_error_read.target
            return

        cls._schema_api_error_read = _schema_api_error_read = AAZObjectType(
            flags={"read_only": True}
        )

        api_error_read = _schema_api_error_read
        api_error_read.code = AAZStrType()
        api_error_read.details = AAZListType()
        api_error_read.innererror = AAZObjectType()
        api_error_read.message = AAZStrType()
        api_error_read.target = AAZStrType()

        details = _schema_api_error_read.details
        details.Element = AAZObjectType()

        _element = _schema_api_error_read.details.Element
        _element.code = AAZStrType()
        _element.message = AAZStrType()
        _element.target = AAZStrType()

        innererror = _schema_api_error_read.innererror
        innererror.errordetail = AAZStrType()
        innererror.exceptiontype = AAZStrType()

        _schema.code = cls._schema_api_error_read.code
        _schema.details = cls._schema_api_error_read.details
        _schema.innererror = cls._schema_api_error_read.innererror
        _schema.message = cls._schema_api_error_read.message
        _schema.target = cls._schema_api_error_read.target


__all__ = ["InstallPatches"]
