"""
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-best-practices.html#which-spot-request-method-to-use

Autogenerated state module using `pop-create-idem <https://gitlab.com/saltstack/pop/pop-create-idem>`__

Note..

The describe function uses the describe_spot_instance_requests to request spot instance details.
The present function uses the request_spot_instances to request creation of a spot instance.
The delete function uses the standard terminate_instances as the cancel_spot_requests does
not terminate an instance that comes online.

If you wish to delete or terminate an instance, and it's a spot instance, you must use the describe
function here to obtain the InstanceID and then use ec2.instance.absent to fully terminate the instance.
"""
from typing import Any
from typing import Dict
from typing import List


__contracts__ = ["resource", "soft_fail"]


async def present(
    hub,
    ctx,
    name: str,
    resource_id: str = None,
    *,
    launch_specification: Dict[str, Any] = None,
    launch_group: str = None,
    spot_price: str = None,
    type: str = None,
    tags: List = None,
    # The following parameters can only be specified at creation
    availability_zone_group: str = None,
    instance_count: int = None,
    instance_interruption_behavior: str = None,
    valid_from: str = None,
    valid_until: str = None,
    **kwargs,
) -> Dict[str, Any]:
    """
    **Autogenerated function**

    Args:
        hub:
        ctx:
        name(Text): An Idem name of the resource.
        resource_id(Text): The spot instance request id
        availability_zone_group(Text): The user-specified name for a logical grouping of requests.
            When you specify an Availability Zone group in a Spot Instance request,
            all Spot Instances in the request are launched in the same Availability Zone.
            Instance proximity is maintained with this parameter, but the choice of
            Availability Zone is not. The group applies only to requests for Spot Instances
            of the same instance type. Any additional Spot Instance requests that are
            specified with the same Availability Zone group name are launched in that
            same Availability Zone, as long as at least one instance from the group is still active.

            If there is no active instance running in the Availability Zone group that
            you specify for a new Spot Instance request (all instances are terminated,
            the request is expired, or the maximum price you specified falls below
            current Spot price), then Amazon EC2 launches the instance in any Availability
            Zone where the constraint can be met. Consequently, the subsequent set of Spot
            Instances could be placed in a different zone from the original request,
            even if you specified the same Availability Zone group.

            Default: Instances are launched in any available Availability Zone.
        instance_count(int): The maximum number of Spot Instances to launch.
        instance_interruption_behavior(str): The behavior when a Spot Instance is interrupted. The default is terminate.
            Valid Values: hibernate | stop | terminate
        launch_group(str):
            The instance launch group. Launch groups are Spot Instances that launch together and terminate together.
            Default: Instances are launched and terminated individually
        launch_specification(Dict[str, Any]): The launch specification.
        spot_price(str): The maximum price per hour that you are willing to pay for a Spot Instance.
            The default is the On-Demand price.
        tags(List, optional):
            The tags to assign to the VPC. Defaults to None.
            * Key (string) -- The key of the tag.
            Tag keys are case-sensitive and accept a maximum of 127 Unicode characters.
            May not begin with aws.
            * Value (string) -- The value of the tag. Tag values are case-sensitive
            and accept a maximum of 255 Unicode characters.
        type(str):
            The Spot Instance request type.
            Default: one-time
            Valid Values: one-time | persistent
        valid_from(str):
            The start date of the request. If this is a one-time request,
            the request becomes active at this date and time and remains
            active until all instances launch, the request expires, or
            the request is canceled. If the request is persistent, the
            request becomes active at this date and time and remains
            active until it expires or is canceled.

            The specified start date and time cannot be equal to the current
            date and time. You must specify a start date and time that
            occurs after the current date and time.
        valid_until(str):
            The end date of the request, in UTC format (YYYY-MM-DDTHH:MM:SSZ).

            For a persistent request, the request remains active until the ValidUntil
            date and time is reached. Otherwise, the request remains active until you cancel it.

            For a one-time request, the request remains active until all instances launch,
            the request is canceled, or the ValidUntil date and time is reached.
            By default, the request is valid for 7 days from the date the request
            was created.

            Type: Timestamp

            Required: No

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_present:
              aws.ec2.spot_instance.present:
                - name: value

        .. code-block:: sls

            resource_is_present:
              aws.ec2.spot_instance.present:
                instance_count: 5
                launch_specification:
                    ImageId: ami-fce3c696
                    KeyName: awskey.pem
                    SecurityGroups: ['sg-709f8709']
                    InstanceType: m4.large
                    Placement:
                        AvailabilityZone: us-east-1a
                    BlockDeviceMappings:
                            Ebs:
                                SnapshotId: snap-f70deff0
                                VolumeSize: 100
                                DeleteOnTermination: True
                                VolumeType: gp2
                                Iops: 300
                                Encrypted: False
                    EbsOptimized: True
                    Monitoring:
                        Enabled: True
                    SecurityGroupIds: sg-709f8709
                spot_price: 0.03
                type: one-time
    """
    desired_state = {
        k: v
        for k, v in locals().items()
        if k not in ("hub", "ctx", "name", "resource_id", "kwargs")
    }
    result = dict(comment=[], old_state=None, new_state=None, name=name, result=True)

    for key in kwargs:
        result["comment"] += [f"Not explicitly supported keyword argument: '{key}'"]

    # Get the resource_id from ESM
    if resource_id is None:
        resource_id = (ctx.old_state or {}).get("resource_id")

    if resource_id:
        # Assume that the spot_instance_request already exists since we have a resource_id
        result["old_state"] = await hub.tool.aws.ec2.spot_instance_request.get(
            ctx, resource_id=resource_id
        )

        if not result["old_state"]:
            result["comment"] += [
                f"Could not find spot_instance_request for '{name}' with existing id '{resource_id}'"
            ]
            return result
        result["comment"] += [f"Spot Instance Request '{name}' already exists"]
    else:
        if ctx.test:
            result["new_state"] = hub.tool.aws.ec2.instance.state.test(**desired_state)
            result["comment"] += [f"Would create aws.ec2.instance '{name}'"]
            return result

        tag_specification = (
            [{"ResourceType": "instance", "Tags": tags}] if tags else None
        )
        # Although it's not specified in the API documentation,
        # apparently 'SecurityGroups' parameter requires the
        # names of the security groups, not the IDs, inside the
        # LaunchSpecification dict
        create_ret = await hub.exec.boto3.client.ec2.request_spot_instances(
            ctx,
            DryRun=False,
            AvailabilityZoneGroup=availability_zone_group,
            InstanceCount=instance_count,
            LaunchGroup=launch_group,
            LaunchSpecification=launch_specification,
            SpotPrice=spot_price,
            Type=type,
            ValidFrom=valid_from,
            ValidUntil=valid_until,
            TagSpecifications=tag_specification,
            InstanceInterruptionBehavior=instance_interruption_behavior,
        )
        result["result"] &= create_ret.result
        if not create_ret:
            result["comment"] += [create_ret.comment]
            return result

        result["comment"] += [f"Created '{name}'"]
        resource_id = create_ret.ret["SpotInstanceRequests"][0]["SpotInstanceRequestId"]

    # Update the spot_instance request now that it exists
    current_state = await hub.tool.aws.ec2.spot_instance_request.get(
        ctx, resource_id=resource_id
    )
    changes_made = False
    for attribute, new_value in desired_state.items():
        if new_value is None:
            # No value has been explicitly given, leave this parameter alone
            continue
        if attribute in (
            "availability_zone_group",
            "instance_count",
            "instance_interruption_behavior",
            "valid_from",
            "valid_until",
        ):
            result["comment"] += [
                f"'{attribute}' is only available on creation of a new spot instance request"
            ]
            continue
        if current_state.get(attribute) != new_value:
            changes_made = True
            if ctx.test:
                result["comment"] += [
                    f"Would update aws.ec2.instance '{name}': {attribute}"
                ]
                continue
            # TODO Update the spot instance request to match the changed parameters
            result["comment"] += [
                f"Currently unable to update aws.ec2.spot_instance_request attribute: {attribute}"
            ]

    # Get the final state of the resource
    if changes_made:
        if ctx.test:
            result["new_state"] = hub.tool.aws.ec2.spot_instance_request.test(
                **desired_state
            )
        else:
            result["new_state"] = await hub.tool.aws.ec2.spot_instance_request.get(
                ctx, resource_id=resource_id
            )
    else:
        result["new_state"] = current_state

    return result


async def absent(hub, ctx, name: str, resource_id: str = None) -> Dict[str, Any]:
    r"""
    **Autogenerated function**

    Cancels one or more Spot Instance requests.

    Args:
        hub:
        ctx:
        name(Text): An Idem name of the resource.
        resource_id(Text): The spot instance request id

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_absent:
              aws.ec2.spot_instance.absent:
                - name: value
    """
    result = dict(
        comment=[], old_state=ctx.old_state, new_state=None, name=name, result=True
    )

    # Get the resource_id from ESM
    if resource_id is None:
        resource_id = (ctx.old_state or {}).get("resource_id")

    # If there still is no resource_id, the instance is gone
    if not resource_id:
        result["comment"] += [f"'{name}' already cancelled"]
        return result

    if ctx.test:
        result["comment"] += [f"Would cancel aws.ec2.spot_instance_request '{name}'"]
        return result

    ret = await hub.exec.boto3.client.ec2.cancel_spot_instance_requests(
        ctx,
        DryRun=False,
        SpotInstanceRequestIds=[resource_id],
    )

    result["result"] &= ret["result"]
    if not result["result"]:
        result["comment"].append(ret["comment"])
        return result
    result["comment"] += [f"cancelled spot instance request '{name}'"]

    return result


async def describe(hub, ctx) -> Dict[str, Dict[str, Any]]:
    """
    Describe the resource in a way that can be recreated/managed with the corresponding "present" function

    Returns:
        Dict[Text, Any]

    Examples:

        .. code-block:: bash

            $ idem describe aws.ec2.spot_instance_request
    """
    result = {}
    ret = await hub.exec.boto3.client.ec2.describe_spot_instance_requests(ctx)

    if not ret:
        hub.log.debug(f"Could not describe spot instance requests: {ret.comment}")
        return {}

    spot_instance_requests = (
        await hub.tool.aws.ec2.spot_instance_request.convert_to_present(ret.ret)
    )

    for resource_id, present_state in spot_instance_requests.items():
        result[resource_id] = {
            "aws.ec2.spot_instance_request.present": [
                {k: v} for k, v in present_state.items()
            ]
        }

    return result


async def search(hub, ctx, name: str, filters: List = None, resource_id: str = None):
    """
    Use an un-managed Instance as a data-source. Supply one of the inputs as the filter.

    Args:
        hub:
        ctx:
        name(Text): The name of the Idem state.
        resource_id(Text, optional): AWS VPC id to identify the resource.
        filters(list, optional): One or more filters: for example, tag :<key>, tag-key.
        A complete list of filters can be found at https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances

    Request Syntax:
        [Idem-state-name]:
          aws.ec2.spot_instance_request.search:
          - resource_id: 'Text'
          - filters:
            - name: 'string'
              values: 'list'
            - name: 'string'
              values: 'list'

        Examples:

            my-unmanaged-spot_instance_request:
              aws.ec2.spot_instance_request.search:
                - resource_id: value
    """
    result = dict(
        comment=[], old_state=ctx.old_state, new_state=None, name=name, result=True
    )

    # Get the resource_id from ESM if this resource used to be managed by "present"
    if not resource_id:
        resource_id = (ctx.old_state or {}).get("resource_id")

    # Perform validation on the parameters
    syntax_validation = hub.tool.aws.search_utils.search_filter_syntax_validation(
        filters=filters
    )
    result["result"] &= syntax_validation["result"]
    if not result["result"]:
        result["comment"].append(syntax_validation["comment"])
        return result

    boto3_filter = hub.tool.aws.search_utils.convert_search_filter_to_boto3(
        filters=filters
    )

    # Get all instances that match the given filters
    ret = await hub.exec.boto3.client.ec2.describe_spot_instance_requests(
        ctx,
        Filters=boto3_filter,
        SpotInstanceRequestIds=[resource_id] if resource_id else None,
    )
    result["result"] &= ret.result
    if not ret:
        result["comment"].append(ret.comment)
        return result

    # Convert the described instances to the present state format
    spot_instance_requests = (
        await hub.tool.aws.ec2.spot_instance_request.convert_to_present(ret.ret)
    )

    # Check for null results
    if not spot_instance_requests:
        result["result"] = False
        result["comment"] += [
            f"Unable to find an aws.ec2.spot_instance_request for '{name}' that matched the given filters"
        ]
        return result

    # Get the first spot_instance_request from the results
    spot_instance_request_id = next(iter(spot_instance_requests.keys()))

    # Add a comment if there were multiple results
    if len(spot_instance_requests) > 1:
        result["comment"] += [
            f"More than one aws.ec2.spot_instance_request resource was found. Use resource '{spot_instance_request_id}'"
        ]

    # Return both old_state and new_state together
    result["new_state"] = spot_instance_requests[spot_instance_request_id]

    return result
