# --------------------------------------------------------------------------------------------
# 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 Update(AAZCommand):
    """Update an existing schedule.
    """

    _aaz_info = {
        "version": "2018-09-15",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.devtestlab/schedules/{}", "2018-09-15"],
        ]
    }

    AZ_SUPPORT_GENERIC_UPDATE = True

    def _handler(self, command_args):
        super()._handler(command_args)
        self._execute_operations()
        return 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 schedule.",
            required=True,
            id_part="name",
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.daily_recurrence = AAZObjectArg(
            options=["--daily-recurrence"],
            arg_group="Properties",
            help="If the schedule will occur once each day of the week, specify the daily recurrence.",
            nullable=True,
        )
        _args_schema.hourly_recurrence = AAZObjectArg(
            options=["--hourly-recurrence"],
            arg_group="Properties",
            help="If the schedule will occur multiple times a day, specify the hourly recurrence.",
            nullable=True,
        )
        _args_schema.notification_settings = AAZObjectArg(
            options=["--notification-settings"],
            arg_group="Properties",
            help="Notification settings.",
            nullable=True,
        )
        _args_schema.status = AAZStrArg(
            options=["--status"],
            arg_group="Properties",
            help="The status of the schedule (i.e. Enabled, Disabled)",
            nullable=True,
            enum={"Disabled": "Disabled", "Enabled": "Enabled"},
        )
        _args_schema.target_resource_id = AAZStrArg(
            options=["--target-resource-id"],
            arg_group="Properties",
            help="The resource ID to which the schedule belongs",
            nullable=True,
        )
        _args_schema.task_type = AAZStrArg(
            options=["--task-type"],
            arg_group="Properties",
            help="The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart).",
            nullable=True,
        )
        _args_schema.time_zone_id = AAZStrArg(
            options=["--time-zone-id"],
            arg_group="Properties",
            help="The time zone ID (e.g. China Standard Time, Greenland Standard Time, Pacific Standard time, etc.). The possible values for this property can be found in `IReadOnlyCollection<string> TimeZoneConverter.TZConvert.KnownWindowsTimeZoneIds` (https://github.com/mattjohnsonpint/TimeZoneConverter/blob/main/README.md)",
            nullable=True,
        )
        _args_schema.weekly_recurrence = AAZObjectArg(
            options=["--weekly-recurrence"],
            arg_group="Properties",
            help="If the schedule will occur only some days of the week, specify the weekly recurrence.",
            nullable=True,
        )

        daily_recurrence = cls._args_schema.daily_recurrence
        daily_recurrence.time = AAZStrArg(
            options=["time"],
            help="The time of day the schedule will occur.",
            nullable=True,
        )

        hourly_recurrence = cls._args_schema.hourly_recurrence
        hourly_recurrence.minute = AAZIntArg(
            options=["minute"],
            help="Minutes of the hour the schedule will run.",
            nullable=True,
        )

        notification_settings = cls._args_schema.notification_settings
        notification_settings.email_recipient = AAZStrArg(
            options=["email-recipient"],
            help="The email recipient to send notifications to (can be a list of semi-colon separated email addresses).",
            nullable=True,
        )
        notification_settings.notification_locale = AAZStrArg(
            options=["notification-locale"],
            help="The locale to use when sending a notification (fallback for unsupported languages is EN).",
            nullable=True,
        )
        notification_settings.status = AAZStrArg(
            options=["status"],
            help="If notifications are enabled for this schedule (i.e. Enabled, Disabled).",
            nullable=True,
            enum={"Disabled": "Disabled", "Enabled": "Enabled"},
        )
        notification_settings.time_in_minutes = AAZIntArg(
            options=["time-in-minutes"],
            help="Time in minutes before event at which notification will be sent.",
            nullable=True,
        )
        notification_settings.webhook_url = AAZStrArg(
            options=["webhook-url"],
            help="The webhook URL to which the notification will be sent.",
            nullable=True,
        )

        weekly_recurrence = cls._args_schema.weekly_recurrence
        weekly_recurrence.time = AAZStrArg(
            options=["time"],
            help="The time of the day the schedule will occur.",
            nullable=True,
        )
        weekly_recurrence.weekdays = AAZListArg(
            options=["weekdays"],
            help="The days of the week for which the schedule is set (e.g. Sunday, Monday, Tuesday, etc.).",
            nullable=True,
        )

        weekdays = cls._args_schema.weekly_recurrence.weekdays
        weekdays.Element = AAZStrArg(
            nullable=True,
        )

        # define Arg Group "Schedule"

        _args_schema = cls._args_schema
        _args_schema.location = AAZResourceLocationArg(
            arg_group="Schedule",
            help="The location of the resource.",
            nullable=True,
        )
        _args_schema.tags = AAZDictArg(
            options=["--tags"],
            arg_group="Schedule",
            help="The tags of the resource.",
            nullable=True,
        )

        tags = cls._args_schema.tags
        tags.Element = AAZStrArg(
            nullable=True,
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.GlobalSchedulesGet(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)
        self.GlobalSchedulesCreateOrUpdate(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 GlobalSchedulesGet(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.DevTestLab/schedules/{name}",
                **self.url_parameters
            )

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

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

        @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", "2018-09-15",
                    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_schedule_read(cls._schema_on_200)

            return cls._schema_on_200

    class GlobalSchedulesCreateOrUpdate(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, 201]:
                return self.on_200_201(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/schedules/{name}",
                **self.url_parameters
            )

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

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

        @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", "2018-09-15",
                    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_schedule_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("location", AAZStrType, ".location")
            _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}})
            _builder.set_prop("tags", AAZDictType, ".tags")

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("dailyRecurrence", AAZObjectType, ".daily_recurrence")
                properties.set_prop("hourlyRecurrence", AAZObjectType, ".hourly_recurrence")
                properties.set_prop("notificationSettings", AAZObjectType, ".notification_settings")
                properties.set_prop("status", AAZStrType, ".status")
                properties.set_prop("targetResourceId", AAZStrType, ".target_resource_id")
                properties.set_prop("taskType", AAZStrType, ".task_type")
                properties.set_prop("timeZoneId", AAZStrType, ".time_zone_id")
                properties.set_prop("weeklyRecurrence", AAZObjectType, ".weekly_recurrence")

            daily_recurrence = _builder.get(".properties.dailyRecurrence")
            if daily_recurrence is not None:
                daily_recurrence.set_prop("time", AAZStrType, ".time")

            hourly_recurrence = _builder.get(".properties.hourlyRecurrence")
            if hourly_recurrence is not None:
                hourly_recurrence.set_prop("minute", AAZIntType, ".minute")

            notification_settings = _builder.get(".properties.notificationSettings")
            if notification_settings is not None:
                notification_settings.set_prop("emailRecipient", AAZStrType, ".email_recipient")
                notification_settings.set_prop("notificationLocale", AAZStrType, ".notification_locale")
                notification_settings.set_prop("status", AAZStrType, ".status")
                notification_settings.set_prop("timeInMinutes", AAZIntType, ".time_in_minutes")
                notification_settings.set_prop("webhookUrl", AAZStrType, ".webhook_url")

            weekly_recurrence = _builder.get(".properties.weeklyRecurrence")
            if weekly_recurrence is not None:
                weekly_recurrence.set_prop("time", AAZStrType, ".time")
                weekly_recurrence.set_prop("weekdays", AAZListType, ".weekdays")

            weekdays = _builder.get(".properties.weeklyRecurrence.weekdays")
            if weekdays is not None:
                weekdays.set_elements(AAZStrType, ".")

            tags = _builder.get(".tags")
            if tags is not None:
                tags.set_elements(AAZStrType, ".")

            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_schedule_read = None

    @classmethod
    def _build_schema_schedule_read(cls, _schema):
        if cls._schema_schedule_read is not None:
            _schema.id = cls._schema_schedule_read.id
            _schema.location = cls._schema_schedule_read.location
            _schema.name = cls._schema_schedule_read.name
            _schema.properties = cls._schema_schedule_read.properties
            _schema.tags = cls._schema_schedule_read.tags
            _schema.type = cls._schema_schedule_read.type
            return

        cls._schema_schedule_read = _schema_schedule_read = AAZObjectType()

        schedule_read = _schema_schedule_read
        schedule_read.id = AAZStrType(
            flags={"read_only": True},
        )
        schedule_read.location = AAZStrType()
        schedule_read.name = AAZStrType(
            flags={"read_only": True},
        )
        schedule_read.properties = AAZObjectType(
            flags={"required": True, "client_flatten": True},
        )
        schedule_read.tags = AAZDictType()
        schedule_read.type = AAZStrType(
            flags={"read_only": True},
        )

        properties = _schema_schedule_read.properties
        properties.created_date = AAZStrType(
            serialized_name="createdDate",
            flags={"read_only": True},
        )
        properties.daily_recurrence = AAZObjectType(
            serialized_name="dailyRecurrence",
        )
        properties.hourly_recurrence = AAZObjectType(
            serialized_name="hourlyRecurrence",
        )
        properties.notification_settings = AAZObjectType(
            serialized_name="notificationSettings",
        )
        properties.provisioning_state = AAZStrType(
            serialized_name="provisioningState",
            flags={"read_only": True},
        )
        properties.status = AAZStrType()
        properties.target_resource_id = AAZStrType(
            serialized_name="targetResourceId",
        )
        properties.task_type = AAZStrType(
            serialized_name="taskType",
        )
        properties.time_zone_id = AAZStrType(
            serialized_name="timeZoneId",
        )
        properties.unique_identifier = AAZStrType(
            serialized_name="uniqueIdentifier",
            flags={"read_only": True},
        )
        properties.weekly_recurrence = AAZObjectType(
            serialized_name="weeklyRecurrence",
        )

        daily_recurrence = _schema_schedule_read.properties.daily_recurrence
        daily_recurrence.time = AAZStrType()

        hourly_recurrence = _schema_schedule_read.properties.hourly_recurrence
        hourly_recurrence.minute = AAZIntType()

        notification_settings = _schema_schedule_read.properties.notification_settings
        notification_settings.email_recipient = AAZStrType(
            serialized_name="emailRecipient",
        )
        notification_settings.notification_locale = AAZStrType(
            serialized_name="notificationLocale",
        )
        notification_settings.status = AAZStrType()
        notification_settings.time_in_minutes = AAZIntType(
            serialized_name="timeInMinutes",
        )
        notification_settings.webhook_url = AAZStrType(
            serialized_name="webhookUrl",
        )

        weekly_recurrence = _schema_schedule_read.properties.weekly_recurrence
        weekly_recurrence.time = AAZStrType()
        weekly_recurrence.weekdays = AAZListType()

        weekdays = _schema_schedule_read.properties.weekly_recurrence.weekdays
        weekdays.Element = AAZStrType()

        tags = _schema_schedule_read.tags
        tags.Element = AAZStrType()

        _schema.id = cls._schema_schedule_read.id
        _schema.location = cls._schema_schedule_read.location
        _schema.name = cls._schema_schedule_read.name
        _schema.properties = cls._schema_schedule_read.properties
        _schema.tags = cls._schema_schedule_read.tags
        _schema.type = cls._schema_schedule_read.type


__all__ = ["Update"]
