# --------------------------------------------------------------------------------------------
# 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(
    "security security-connector devops azuredevopsorg project repo update",
    is_preview=True,
)
class Update(AAZCommand):
    """Update a monitored Azure DevOps repository resource.

    :example: Disable pull request annotations
        az security security-connectors devops azuredevopsorgs projects repos update --security-connector-name myConnectorName --resource-group myResourceGroup --org-name myOrganization --project-name myProject --repo-name myRepo  --actionable-remediation state=Disabled

    :example: Enable pull request annotations with minimum severity level
        az security security-connectors devops azuredevopsorgs projects repos update --security-connector-name myConnectorName --resource-group myResourceGroup --org-name myOrganization --project-name myProject --repo-name myRepo  --actionable-remediation state=Enabled category-configurations[0].category=IaC category-configurations[0].minimum-severity-level=Low
    """

    _aaz_info = {
        "version": "2023-09-01-preview",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.security/securityconnectors/{}/devops/default/azuredevopsorgs/{}/projects/{}/repos/{}", "2023-09-01-preview"],
        ]
    }

    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.org_name = AAZStrArg(
            options=["--org-name"],
            help="The Azure DevOps organization name.",
            required=True,
            id_part="child_name_2",
        )
        _args_schema.project_name = AAZStrArg(
            options=["--project-name"],
            help="The project name.",
            required=True,
            id_part="child_name_3",
        )
        _args_schema.repo_name = AAZStrArg(
            options=["--repo-name"],
            help="The repository name.",
            required=True,
            id_part="child_name_4",
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.security_connector_name = AAZStrArg(
            options=["-n", "--name", "--security-connector-name"],
            help="The security connector name.",
            required=True,
            id_part="name",
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.actionable_remediation = AAZObjectArg(
            options=["--actionable-remediation"],
            arg_group="Properties",
            help="Configuration payload for PR Annotations.",
        )

        actionable_remediation = cls._args_schema.actionable_remediation
        actionable_remediation.branch_configuration = AAZObjectArg(
            options=["branch-configuration"],
            help="Repository branch configuration for PR Annotations.",
        )
        actionable_remediation.category_configurations = AAZListArg(
            options=["category-configurations"],
            help="Gets or sets list of categories and severity levels.",
        )
        actionable_remediation.inherit_from_parent_state = AAZStrArg(
            options=["inherit-from-parent-state"],
            help="Update Settings. Enabled - Resource should inherit configurations from parent. Disabled - Resource should not inherit configurations from parent.",
            enum={"Disabled": "Disabled", "Enabled": "Enabled"},
        )
        actionable_remediation.state = AAZStrArg(
            options=["state"],
            help="ActionableRemediation Setting. None - the setting was never set. Enabled - ActionableRemediation is enabled. Disabled - ActionableRemediation is disabled.",
            enum={"Disabled": "Disabled", "Enabled": "Enabled", "None": "None"},
        )

        branch_configuration = cls._args_schema.actionable_remediation.branch_configuration
        branch_configuration.annotate_default_branch = AAZStrArg(
            options=["annotate-default-branch"],
            help="Configuration of PR Annotations on default branch. Enabled - PR Annotations are enabled on the resource's default branch. Disabled - PR Annotations are disabled on the resource's default branch.",
            enum={"Disabled": "Disabled", "Enabled": "Enabled"},
        )
        branch_configuration.branch_names = AAZListArg(
            options=["branch-names"],
            help="Gets or sets branches that should have annotations.",
        )

        branch_names = cls._args_schema.actionable_remediation.branch_configuration.branch_names
        branch_names.Element = AAZStrArg()

        category_configurations = cls._args_schema.actionable_remediation.category_configurations
        category_configurations.Element = AAZObjectArg()

        _element = cls._args_schema.actionable_remediation.category_configurations.Element
        _element.category = AAZStrArg(
            options=["category"],
            help="Rule categories. Code - code scanning results. Artifact scanning results. Dependencies scanning results. IaC results. Secrets scanning results. Container scanning results.",
            enum={"Artifacts": "Artifacts", "Code": "Code", "Containers": "Containers", "Dependencies": "Dependencies", "IaC": "IaC", "Secrets": "Secrets"},
        )
        _element.minimum_severity_level = AAZStrArg(
            options=["minimum-severity-level"],
            help="Gets or sets minimum severity level for a given category.",
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.AzureDevOpsReposUpdate(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 AzureDevOpsReposUpdate(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": "azure-async-operation"},
                    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": "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.Security/securityConnectors/{securityConnectorName}/devops/default/azureDevOpsOrgs/{orgName}/projects/{projectName}/repos/{repoName}",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "orgName", self.ctx.args.org_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "projectName", self.ctx.args.project_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "repoName", self.ctx.args.repo_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "securityConnectorName", self.ctx.args.security_connector_name,
                    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", "2023-09-01-preview",
                    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("properties", AAZObjectType)

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("actionableRemediation", AAZObjectType, ".actionable_remediation")

            actionable_remediation = _builder.get(".properties.actionableRemediation")
            if actionable_remediation is not None:
                actionable_remediation.set_prop("branchConfiguration", AAZObjectType, ".branch_configuration")
                actionable_remediation.set_prop("categoryConfigurations", AAZListType, ".category_configurations")
                actionable_remediation.set_prop("inheritFromParentState", AAZStrType, ".inherit_from_parent_state")
                actionable_remediation.set_prop("state", AAZStrType, ".state")

            branch_configuration = _builder.get(".properties.actionableRemediation.branchConfiguration")
            if branch_configuration is not None:
                branch_configuration.set_prop("annotateDefaultBranch", AAZStrType, ".annotate_default_branch")
                branch_configuration.set_prop("branchNames", AAZListType, ".branch_names")

            branch_names = _builder.get(".properties.actionableRemediation.branchConfiguration.branchNames")
            if branch_names is not None:
                branch_names.set_elements(AAZStrType, ".")

            category_configurations = _builder.get(".properties.actionableRemediation.categoryConfigurations")
            if category_configurations is not None:
                category_configurations.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.actionableRemediation.categoryConfigurations[]")
            if _elements is not None:
                _elements.set_prop("category", AAZStrType, ".category")
                _elements.set_prop("minimumSeverityLevel", AAZStrType, ".minimum_severity_level")

            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()
            _UpdateHelper._build_schema_azure_dev_ops_repository_read(cls._schema_on_200)

            return cls._schema_on_200


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

    _schema_azure_dev_ops_repository_read = None

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

        cls._schema_azure_dev_ops_repository_read = _schema_azure_dev_ops_repository_read = AAZObjectType()

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

        properties = _schema_azure_dev_ops_repository_read.properties
        properties.actionable_remediation = AAZObjectType(
            serialized_name="actionableRemediation",
        )
        properties.onboarding_state = AAZStrType(
            serialized_name="onboardingState",
        )
        properties.parent_org_name = AAZStrType(
            serialized_name="parentOrgName",
        )
        properties.parent_project_name = AAZStrType(
            serialized_name="parentProjectName",
        )
        properties.provisioning_state = AAZStrType(
            serialized_name="provisioningState",
        )
        properties.provisioning_status_message = AAZStrType(
            serialized_name="provisioningStatusMessage",
            flags={"read_only": True},
        )
        properties.provisioning_status_update_time_utc = AAZStrType(
            serialized_name="provisioningStatusUpdateTimeUtc",
            flags={"read_only": True},
        )
        properties.repo_id = AAZStrType(
            serialized_name="repoId",
            flags={"read_only": True},
        )
        properties.repo_url = AAZStrType(
            serialized_name="repoUrl",
            flags={"read_only": True},
        )
        properties.visibility = AAZStrType(
            flags={"read_only": True},
        )

        actionable_remediation = _schema_azure_dev_ops_repository_read.properties.actionable_remediation
        actionable_remediation.branch_configuration = AAZObjectType(
            serialized_name="branchConfiguration",
        )
        actionable_remediation.category_configurations = AAZListType(
            serialized_name="categoryConfigurations",
        )
        actionable_remediation.inherit_from_parent_state = AAZStrType(
            serialized_name="inheritFromParentState",
        )
        actionable_remediation.state = AAZStrType()

        branch_configuration = _schema_azure_dev_ops_repository_read.properties.actionable_remediation.branch_configuration
        branch_configuration.annotate_default_branch = AAZStrType(
            serialized_name="annotateDefaultBranch",
        )
        branch_configuration.branch_names = AAZListType(
            serialized_name="branchNames",
        )

        branch_names = _schema_azure_dev_ops_repository_read.properties.actionable_remediation.branch_configuration.branch_names
        branch_names.Element = AAZStrType()

        category_configurations = _schema_azure_dev_ops_repository_read.properties.actionable_remediation.category_configurations
        category_configurations.Element = AAZObjectType()

        _element = _schema_azure_dev_ops_repository_read.properties.actionable_remediation.category_configurations.Element
        _element.category = AAZStrType()
        _element.minimum_severity_level = AAZStrType(
            serialized_name="minimumSeverityLevel",
        )

        system_data = _schema_azure_dev_ops_repository_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_azure_dev_ops_repository_read.id
        _schema.name = cls._schema_azure_dev_ops_repository_read.name
        _schema.properties = cls._schema_azure_dev_ops_repository_read.properties
        _schema.system_data = cls._schema_azure_dev_ops_repository_read.system_data
        _schema.type = cls._schema_azure_dev_ops_repository_read.type


__all__ = ["Update"]
