text:
# This file is auto-generated by AWSMetadata.jl
using AWS
using AWS.AWSServices: network_firewall
using AWS.Compat
using AWS.UUIDs

"""
    associate_firewall_policy(firewall_policy_arn)
    associate_firewall_policy(firewall_policy_arn, params::Dict{String,<:Any})

Associates a FirewallPolicy to a Firewall.  A firewall policy defines how to monitor and
manage your VPC network traffic, using a collection of inspection rule groups and other
settings. Each firewall requires one firewall policy association, and you can use the same
firewall policy for multiple firewalls.

# Arguments
- `firewall_policy_arn`: The Amazon Resource Name (ARN) of the firewall policy.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"UpdateToken"`: An optional token that you can use for optimistic locking. Network
  Firewall returns a token to your requests that access the firewall. The token marks the
  state of the firewall resource at the time of the request.  To make an unconditional change
  to the firewall, omit the token in your update request. Without the token, Network Firewall
  performs your updates regardless of whether the firewall has changed since you last
  retrieved it. To make a conditional change to the firewall, provide the token in your
  update request. Network Firewall uses the token to ensure that the firewall hasn't changed
  since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the firewall again to get a current copy
  of it with a new token. Reapply your changes as needed, then try the operation again using
  the new token.
"""
function associate_firewall_policy(
    FirewallPolicyArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "AssociateFirewallPolicy",
        Dict{String,Any}("FirewallPolicyArn" => FirewallPolicyArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function associate_firewall_policy(
    FirewallPolicyArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "AssociateFirewallPolicy",
        Dict{String,Any}(
            mergewith(
                _merge, Dict{String,Any}("FirewallPolicyArn" => FirewallPolicyArn), params
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    associate_subnets(subnet_mappings)
    associate_subnets(subnet_mappings, params::Dict{String,<:Any})

Associates the specified subnets in the Amazon VPC to the firewall. You can specify one
subnet for each of the Availability Zones that the VPC spans.  This request creates an AWS
Network Firewall firewall endpoint in each of the subnets. To enable the firewall's
protections, you must also modify the VPC's route tables for each subnet's Availability
Zone, to redirect the traffic that's coming into and going out of the zone through the
firewall endpoint.

# Arguments
- `subnet_mappings`: The IDs of the subnets that you want to associate with the firewall.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"UpdateToken"`: An optional token that you can use for optimistic locking. Network
  Firewall returns a token to your requests that access the firewall. The token marks the
  state of the firewall resource at the time of the request.  To make an unconditional change
  to the firewall, omit the token in your update request. Without the token, Network Firewall
  performs your updates regardless of whether the firewall has changed since you last
  retrieved it. To make a conditional change to the firewall, provide the token in your
  update request. Network Firewall uses the token to ensure that the firewall hasn't changed
  since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the firewall again to get a current copy
  of it with a new token. Reapply your changes as needed, then try the operation again using
  the new token.
"""
function associate_subnets(
    SubnetMappings; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "AssociateSubnets",
        Dict{String,Any}("SubnetMappings" => SubnetMappings);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function associate_subnets(
    SubnetMappings,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "AssociateSubnets",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SubnetMappings" => SubnetMappings), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_firewall(firewall_name, firewall_policy_arn, subnet_mappings, vpc_id)
    create_firewall(firewall_name, firewall_policy_arn, subnet_mappings, vpc_id, params::Dict{String,<:Any})

Creates an AWS Network Firewall Firewall and accompanying FirewallStatus for a VPC.  The
firewall defines the configuration settings for an AWS Network Firewall firewall. The
settings that you can define at creation include the firewall policy, the subnets in your
VPC to use for the firewall endpoints, and any tags that are attached to the firewall AWS
resource.  After you create a firewall, you can provide additional settings, like the
logging configuration.  To update the settings for a firewall, you use the operations that
apply to the settings themselves, for example UpdateLoggingConfiguration, AssociateSubnets,
and UpdateFirewallDeleteProtection.  To manage a firewall's tags, use the standard AWS
resource tagging operations, ListTagsForResource, TagResource, and UntagResource. To
retrieve information about firewalls, use ListFirewalls and DescribeFirewall.

# Arguments
- `firewall_name`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it.
- `firewall_policy_arn`: The Amazon Resource Name (ARN) of the FirewallPolicy that you want
  to use for the firewall.
- `subnet_mappings`: The public subnets to use for your Network Firewall firewalls. Each
  subnet must belong to a different Availability Zone in the VPC. Network Firewall creates a
  firewall endpoint in each subnet.
- `vpc_id`: The unique identifier of the VPC where Network Firewall should create the
  firewall.  You can't change this setting after you create the firewall.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"DeleteProtection"`: A flag indicating whether it is possible to delete the firewall. A
  setting of TRUE indicates that the firewall is protected against deletion. Use this setting
  to protect against accidentally deleting a firewall that is in use. When you create a
  firewall, the operation initializes this flag to TRUE.
- `"Description"`: A description of the firewall.
- `"FirewallPolicyChangeProtection"`: A setting indicating whether the firewall is
  protected against a change to the firewall policy association. Use this setting to protect
  against accidentally modifying the firewall policy for a firewall that is in use. When you
  create a firewall, the operation initializes this setting to TRUE.
- `"SubnetChangeProtection"`: A setting indicating whether the firewall is protected
  against changes to the subnet associations. Use this setting to protect against
  accidentally modifying the subnet associations for a firewall that is in use. When you
  create a firewall, the operation initializes this setting to TRUE.
- `"Tags"`: The key:value pairs to associate with the resource.
"""
function create_firewall(
    FirewallName,
    FirewallPolicyArn,
    SubnetMappings,
    VpcId;
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "CreateFirewall",
        Dict{String,Any}(
            "FirewallName" => FirewallName,
            "FirewallPolicyArn" => FirewallPolicyArn,
            "SubnetMappings" => SubnetMappings,
            "VpcId" => VpcId,
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_firewall(
    FirewallName,
    FirewallPolicyArn,
    SubnetMappings,
    VpcId,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "CreateFirewall",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "FirewallName" => FirewallName,
                    "FirewallPolicyArn" => FirewallPolicyArn,
                    "SubnetMappings" => SubnetMappings,
                    "VpcId" => VpcId,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_firewall_policy(firewall_policy, firewall_policy_name)
    create_firewall_policy(firewall_policy, firewall_policy_name, params::Dict{String,<:Any})

Creates the firewall policy for the firewall according to the specifications.  An AWS
Network Firewall firewall policy defines the behavior of a firewall, in a collection of
stateless and stateful rule groups and other settings. You can use one firewall policy for
multiple firewalls.

# Arguments
- `firewall_policy`: The rule groups and policy actions to use in the firewall policy.
- `firewall_policy_name`: The descriptive name of the firewall policy. You can't change the
  name of a firewall policy after you create it.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: A description of the firewall policy.
- `"DryRun"`: Indicates whether you want Network Firewall to just check the validity of the
  request, rather than run the request.  If set to TRUE, Network Firewall checks whether the
  request can run successfully, but doesn't actually make the requested changes. The call
  returns the value that the request would return if you ran it with dry run set to FALSE,
  but doesn't make additions or changes to your resources. This option allows you to make
  sure that you have the required permissions to run the request and that your request
  parameters are valid.  If set to FALSE, Network Firewall makes the requested changes to
  your resources.
- `"Tags"`: The key:value pairs to associate with the resource.
"""
function create_firewall_policy(
    FirewallPolicy, FirewallPolicyName; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "CreateFirewallPolicy",
        Dict{String,Any}(
            "FirewallPolicy" => FirewallPolicy, "FirewallPolicyName" => FirewallPolicyName
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_firewall_policy(
    FirewallPolicy,
    FirewallPolicyName,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "CreateFirewallPolicy",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "FirewallPolicy" => FirewallPolicy,
                    "FirewallPolicyName" => FirewallPolicyName,
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    create_rule_group(capacity, rule_group_name, type)
    create_rule_group(capacity, rule_group_name, type, params::Dict{String,<:Any})

Creates the specified stateless or stateful rule group, which includes the rules for
network traffic inspection, a capacity setting, and tags.  You provide your rule group
specification in your request using either RuleGroup or Rules.

# Arguments
- `capacity`: The maximum operating resources that this rule group can use. Rule group
  capacity is fixed at creation. When you update a rule group, you are limited to this
  capacity. When you reference a rule group from a firewall policy, Network Firewall reserves
  this capacity for the rule group.  You can retrieve the capacity that would be required for
  a rule group before you create the rule group by calling CreateRuleGroup with DryRun set to
  TRUE.   You can't change or exceed this capacity when you update the rule group, so leave
  room for your rule group to grow.    Capacity for a stateless rule group  For a stateless
  rule group, the capacity required is the sum of the capacity requirements of the individual
  rules that you expect to have in the rule group.  To calculate the capacity requirement of
  a single rule, multiply the capacity requirement values of each of the rule's match
  settings:   A match setting with no criteria specified has a value of 1.    A match setting
  with Any specified has a value of 1.    All other match settings have a value equal to the
  number of elements provided in the setting. For example, a protocol setting [\"UDP\"] and a
  source setting [\"10.0.0.0/24\"] each have a value of 1. A protocol setting
  [\"UDP\",\"TCP\"] has a value of 2. A source setting
  [\"10.0.0.0/24\",\"10.0.0.1/24\",\"10.0.0.2/24\"] has a value of 3.    A rule with no
  criteria specified in any of its match settings has a capacity requirement of 1. A rule
  with protocol setting [\"UDP\",\"TCP\"], source setting
  [\"10.0.0.0/24\",\"10.0.0.1/24\",\"10.0.0.2/24\"], and a single specification or no
  specification for each of the other match settings has a capacity requirement of 6.
  Capacity for a stateful rule group  For a stateful rule group, the minimum capacity
  required is the number of individual rules that you expect to have in the rule group.
- `rule_group_name`: The descriptive name of the rule group. You can't change the name of a
  rule group after you create it.
- `type`: Indicates whether the rule group is stateless or stateful. If the rule group is
  stateless, it contains stateless rules. If it is stateful, it contains stateful rules.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: A description of the rule group.
- `"DryRun"`: Indicates whether you want Network Firewall to just check the validity of the
  request, rather than run the request.  If set to TRUE, Network Firewall checks whether the
  request can run successfully, but doesn't actually make the requested changes. The call
  returns the value that the request would return if you ran it with dry run set to FALSE,
  but doesn't make additions or changes to your resources. This option allows you to make
  sure that you have the required permissions to run the request and that your request
  parameters are valid.  If set to FALSE, Network Firewall makes the requested changes to
  your resources.
- `"RuleGroup"`: An object that defines the rule group rules.   You must provide either
  this rule group setting or a Rules setting, but not both.
- `"Rules"`: A string containing stateful rule group rules specifications in Suricata flat
  format, with one rule per line. Use this to import your existing Suricata compatible rule
  groups.   You must provide either this rules setting or a populated RuleGroup setting, but
  not both.   You can provide your rule group specification in Suricata flat format through
  this setting when you create or update your rule group. The call response returns a
  RuleGroup object that Network Firewall has populated from your string.
- `"Tags"`: The key:value pairs to associate with the resource.
"""
function create_rule_group(
    Capacity, RuleGroupName, Type; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "CreateRuleGroup",
        Dict{String,Any}(
            "Capacity" => Capacity, "RuleGroupName" => RuleGroupName, "Type" => Type
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function create_rule_group(
    Capacity,
    RuleGroupName,
    Type,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "CreateRuleGroup",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "Capacity" => Capacity, "RuleGroupName" => RuleGroupName, "Type" => Type
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_firewall()
    delete_firewall(params::Dict{String,<:Any})

Deletes the specified Firewall and its FirewallStatus. This operation requires the
firewall's DeleteProtection flag to be FALSE. You can't revert this operation.  You can
check whether a firewall is in use by reviewing the route tables for the Availability Zones
where you have firewall subnet mappings. Retrieve the subnet mappings by calling
DescribeFirewall. You define and update the route tables through Amazon VPC. As needed,
update the route tables for the zones to remove the firewall endpoints. When the route
tables no longer use the firewall endpoints, you can remove the firewall safely. To delete
a firewall, remove the delete protection if you need to using
UpdateFirewallDeleteProtection, then delete the firewall by calling DeleteFirewall.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
"""
function delete_firewall(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DeleteFirewall"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function delete_firewall(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DeleteFirewall", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    delete_firewall_policy()
    delete_firewall_policy(params::Dict{String,<:Any})

Deletes the specified FirewallPolicy.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallPolicyArn"`: The Amazon Resource Name (ARN) of the firewall policy. You must
  specify the ARN or the name, and you can specify both.
- `"FirewallPolicyName"`: The descriptive name of the firewall policy. You can't change the
  name of a firewall policy after you create it. You must specify the ARN or the name, and
  you can specify both.
"""
function delete_firewall_policy(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DeleteFirewallPolicy"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function delete_firewall_policy(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DeleteFirewallPolicy",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_resource_policy(resource_arn)
    delete_resource_policy(resource_arn, params::Dict{String,<:Any})

Deletes a resource policy that you created in a PutResourcePolicy request.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the rule group or firewall policy whose
  resource policy you want to delete.

"""
function delete_resource_policy(
    ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DeleteResourcePolicy",
        Dict{String,Any}("ResourceArn" => ResourceArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function delete_resource_policy(
    ResourceArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "DeleteResourcePolicy",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ResourceArn" => ResourceArn), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    delete_rule_group()
    delete_rule_group(params::Dict{String,<:Any})

Deletes the specified RuleGroup.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"RuleGroupArn"`: The Amazon Resource Name (ARN) of the rule group. You must specify the
  ARN or the name, and you can specify both.
- `"RuleGroupName"`: The descriptive name of the rule group. You can't change the name of a
  rule group after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"Type"`: Indicates whether the rule group is stateless or stateful. If the rule group is
  stateless, it contains stateless rules. If it is stateful, it contains stateful rules.
  This setting is required for requests that do not include the RuleGroupARN.
"""
function delete_rule_group(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DeleteRuleGroup"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function delete_rule_group(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DeleteRuleGroup", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    describe_firewall()
    describe_firewall(params::Dict{String,<:Any})

Returns the data objects for the specified firewall.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
"""
function describe_firewall(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DescribeFirewall"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function describe_firewall(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DescribeFirewall", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    describe_firewall_policy()
    describe_firewall_policy(params::Dict{String,<:Any})

Returns the data objects for the specified firewall policy.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallPolicyArn"`: The Amazon Resource Name (ARN) of the firewall policy. You must
  specify the ARN or the name, and you can specify both.
- `"FirewallPolicyName"`: The descriptive name of the firewall policy. You can't change the
  name of a firewall policy after you create it. You must specify the ARN or the name, and
  you can specify both.
"""
function describe_firewall_policy(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DescribeFirewallPolicy"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function describe_firewall_policy(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DescribeFirewallPolicy",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_logging_configuration()
    describe_logging_configuration(params::Dict{String,<:Any})

Returns the logging configuration for the specified firewall.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
"""
function describe_logging_configuration(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DescribeLoggingConfiguration";
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_logging_configuration(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DescribeLoggingConfiguration",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_resource_policy(resource_arn)
    describe_resource_policy(resource_arn, params::Dict{String,<:Any})

Retrieves a resource policy that you created in a PutResourcePolicy request.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the rule group or firewall policy whose
  resource policy you want to retrieve.

"""
function describe_resource_policy(
    ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DescribeResourcePolicy",
        Dict{String,Any}("ResourceArn" => ResourceArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function describe_resource_policy(
    ResourceArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "DescribeResourcePolicy",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ResourceArn" => ResourceArn), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    describe_rule_group()
    describe_rule_group(params::Dict{String,<:Any})

Returns the data objects for the specified rule group.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"RuleGroupArn"`: The Amazon Resource Name (ARN) of the rule group. You must specify the
  ARN or the name, and you can specify both.
- `"RuleGroupName"`: The descriptive name of the rule group. You can't change the name of a
  rule group after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"Type"`: Indicates whether the rule group is stateless or stateful. If the rule group is
  stateless, it contains stateless rules. If it is stateful, it contains stateful rules.
  This setting is required for requests that do not include the RuleGroupARN.
"""
function describe_rule_group(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DescribeRuleGroup"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function describe_rule_group(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DescribeRuleGroup", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    describe_rule_group_metadata()
    describe_rule_group_metadata(params::Dict{String,<:Any})

High-level information about a rule group, returned by operations like create and describe.
You can use the information provided in the metadata to retrieve and manage a rule group.
You can retrieve all objects for a rule group by calling DescribeRuleGroup.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"RuleGroupArn"`: The descriptive name of the rule group. You can't change the name of a
  rule group after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"RuleGroupName"`: The descriptive name of the rule group. You can't change the name of a
  rule group after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"Type"`: Indicates whether the rule group is stateless or stateful. If the rule group is
  stateless, it contains stateless rules. If it is stateful, it contains stateful rules.
  This setting is required for requests that do not include the RuleGroupARN.
"""
function describe_rule_group_metadata(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DescribeRuleGroupMetadata"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function describe_rule_group_metadata(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "DescribeRuleGroupMetadata",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    disassociate_subnets(subnet_ids)
    disassociate_subnets(subnet_ids, params::Dict{String,<:Any})

Removes the specified subnet associations from the firewall. This removes the firewall
endpoints from the subnets and removes any network filtering protections that the endpoints
were providing.

# Arguments
- `subnet_ids`: The unique identifiers for the subnets that you want to disassociate.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"UpdateToken"`: An optional token that you can use for optimistic locking. Network
  Firewall returns a token to your requests that access the firewall. The token marks the
  state of the firewall resource at the time of the request.  To make an unconditional change
  to the firewall, omit the token in your update request. Without the token, Network Firewall
  performs your updates regardless of whether the firewall has changed since you last
  retrieved it. To make a conditional change to the firewall, provide the token in your
  update request. Network Firewall uses the token to ensure that the firewall hasn't changed
  since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the firewall again to get a current copy
  of it with a new token. Reapply your changes as needed, then try the operation again using
  the new token.
"""
function disassociate_subnets(SubnetIds; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "DisassociateSubnets",
        Dict{String,Any}("SubnetIds" => SubnetIds);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function disassociate_subnets(
    SubnetIds,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "DisassociateSubnets",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("SubnetIds" => SubnetIds), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_firewall_policies()
    list_firewall_policies(params::Dict{String,<:Any})

Retrieves the metadata for the firewall policies that you have defined. Depending on your
setting for max results and the number of firewall policies, a single call might not return
the full list.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of objects that you want Network Firewall to return
  for this request. If more objects are available, in the response, Network Firewall provides
  a NextToken value that you can use in a subsequent call to get the next batch of objects.
- `"NextToken"`: When you request a list of objects with a MaxResults setting, if the
  number of objects that are still available for retrieval exceeds the maximum you requested,
  Network Firewall returns a NextToken value in the response. To retrieve the next batch of
  objects, use the token returned from the prior request in your next request.
"""
function list_firewall_policies(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "ListFirewallPolicies"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_firewall_policies(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "ListFirewallPolicies",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    list_firewalls()
    list_firewalls(params::Dict{String,<:Any})

Retrieves the metadata for the firewalls that you have defined. If you provide VPC
identifiers in your request, this returns only the firewalls for those VPCs. Depending on
your setting for max results and the number of firewalls, a single call might not return
the full list.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of objects that you want Network Firewall to return
  for this request. If more objects are available, in the response, Network Firewall provides
  a NextToken value that you can use in a subsequent call to get the next batch of objects.
- `"NextToken"`: When you request a list of objects with a MaxResults setting, if the
  number of objects that are still available for retrieval exceeds the maximum you requested,
  Network Firewall returns a NextToken value in the response. To retrieve the next batch of
  objects, use the token returned from the prior request in your next request.
- `"VpcIds"`: The unique identifiers of the VPCs that you want Network Firewall to retrieve
  the firewalls for. Leave this blank to retrieve all firewalls that you have defined.
"""
function list_firewalls(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "ListFirewalls"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_firewalls(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "ListFirewalls", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    list_rule_groups()
    list_rule_groups(params::Dict{String,<:Any})

Retrieves the metadata for the rule groups that you have defined. Depending on your setting
for max results and the number of rule groups, a single call might not return the full
list.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of objects that you want Network Firewall to return
  for this request. If more objects are available, in the response, Network Firewall provides
  a NextToken value that you can use in a subsequent call to get the next batch of objects.
- `"NextToken"`: When you request a list of objects with a MaxResults setting, if the
  number of objects that are still available for retrieval exceeds the maximum you requested,
  Network Firewall returns a NextToken value in the response. To retrieve the next batch of
  objects, use the token returned from the prior request in your next request.
- `"Scope"`: The scope of the request. The default setting of ACCOUNT or a setting of NULL
  returns all of the rule groups in your account. A setting of MANAGED returns all available
  managed rule groups.
"""
function list_rule_groups(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "ListRuleGroups"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function list_rule_groups(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "ListRuleGroups", params; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end

"""
    list_tags_for_resource(resource_arn)
    list_tags_for_resource(resource_arn, params::Dict{String,<:Any})

Retrieves the tags associated with the specified resource. Tags are key:value pairs that
you can use to categorize and manage your resources, for purposes like billing. For
example, you might set the tag key to \"customer\" and the value to the customer name or
ID. You can specify one or more tags to add to each AWS resource, up to 50 tags for a
resource. You can tag the AWS resources that you manage through AWS Network Firewall:
firewalls, firewall policies, and rule groups.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"MaxResults"`: The maximum number of objects that you want Network Firewall to return
  for this request. If more objects are available, in the response, Network Firewall provides
  a NextToken value that you can use in a subsequent call to get the next batch of objects.
- `"NextToken"`: When you request a list of objects with a MaxResults setting, if the
  number of objects that are still available for retrieval exceeds the maximum you requested,
  Network Firewall returns a NextToken value in the response. To retrieve the next batch of
  objects, use the token returned from the prior request in your next request.
"""
function list_tags_for_resource(
    ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "ListTagsForResource",
        Dict{String,Any}("ResourceArn" => ResourceArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function list_tags_for_resource(
    ResourceArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "ListTagsForResource",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("ResourceArn" => ResourceArn), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    put_resource_policy(policy, resource_arn)
    put_resource_policy(policy, resource_arn, params::Dict{String,<:Any})

Creates or updates an AWS Identity and Access Management policy for your rule group or
firewall policy. Use this to share rule groups and firewall policies between accounts. This
operation works in conjunction with the AWS Resource Access Manager (RAM) service to manage
resource sharing for Network Firewall.  Use this operation to create or update a resource
policy for your rule group or firewall policy. In the policy, you specify the accounts that
you want to share the resource with and the operations that you want the accounts to be
able to perform.  When you add an account in the resource policy, you then run the
following Resource Access Manager (RAM) operations to access and accept the shared rule
group or firewall policy.     GetResourceShareInvitations - Returns the Amazon Resource
Names (ARNs) of the resource share invitations.     AcceptResourceShareInvitation - Accepts
the share invitation for a specified resource share.    For additional information about
resource sharing using RAM, see AWS Resource Access Manager User Guide.

# Arguments
- `policy`: The AWS Identity and Access Management policy statement that lists the accounts
  that you want to share your rule group or firewall policy with and the operations that you
  want the accounts to be able to perform.  For a rule group resource, you can specify the
  following operations in the Actions section of the statement:
  network-firewall:CreateFirewallPolicy   network-firewall:UpdateFirewallPolicy
  network-firewall:ListRuleGroups   For a firewall policy resource, you can specify the
  following operations in the Actions section of the statement:
  network-firewall:CreateFirewall   network-firewall:UpdateFirewall
  network-firewall:AssociateFirewallPolicy   network-firewall:ListFirewallPolicies   In the
  Resource section of the statement, you specify the ARNs for the rule groups and firewall
  policies that you want to share with the account that you specified in Arn.
- `resource_arn`: The Amazon Resource Name (ARN) of the account that you want to share rule
  groups and firewall policies with.

"""
function put_resource_policy(
    Policy, ResourceArn; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "PutResourcePolicy",
        Dict{String,Any}("Policy" => Policy, "ResourceArn" => ResourceArn);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function put_resource_policy(
    Policy,
    ResourceArn,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "PutResourcePolicy",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("Policy" => Policy, "ResourceArn" => ResourceArn),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    tag_resource(resource_arn, tags)
    tag_resource(resource_arn, tags, params::Dict{String,<:Any})

Adds the specified tags to the specified resource. Tags are key:value pairs that you can
use to categorize and manage your resources, for purposes like billing. For example, you
might set the tag key to \"customer\" and the value to the customer name or ID. You can
specify one or more tags to add to each AWS resource, up to 50 tags for a resource. You can
tag the AWS resources that you manage through AWS Network Firewall: firewalls, firewall
policies, and rule groups.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource.
- `tags`:

"""
function tag_resource(ResourceArn, Tags; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "TagResource",
        Dict{String,Any}("ResourceArn" => ResourceArn, "Tags" => Tags);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function tag_resource(
    ResourceArn,
    Tags,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "TagResource",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("ResourceArn" => ResourceArn, "Tags" => Tags),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    untag_resource(resource_arn, tag_keys)
    untag_resource(resource_arn, tag_keys, params::Dict{String,<:Any})

Removes the tags with the specified keys from the specified resource. Tags are key:value
pairs that you can use to categorize and manage your resources, for purposes like billing.
For example, you might set the tag key to \"customer\" and the value to the customer name
or ID. You can specify one or more tags to add to each AWS resource, up to 50 tags for a
resource. You can manage tags for the AWS resources that you manage through AWS Network
Firewall: firewalls, firewall policies, and rule groups.

# Arguments
- `resource_arn`: The Amazon Resource Name (ARN) of the resource.
- `tag_keys`:

"""
function untag_resource(
    ResourceArn, TagKeys; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "UntagResource",
        Dict{String,Any}("ResourceArn" => ResourceArn, "TagKeys" => TagKeys);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function untag_resource(
    ResourceArn,
    TagKeys,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "UntagResource",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("ResourceArn" => ResourceArn, "TagKeys" => TagKeys),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_firewall_delete_protection(delete_protection)
    update_firewall_delete_protection(delete_protection, params::Dict{String,<:Any})

Modifies the flag, DeleteProtection, which indicates whether it is possible to delete the
firewall. If the flag is set to TRUE, the firewall is protected against deletion. This
setting helps protect against accidentally deleting a firewall that's in use.

# Arguments
- `delete_protection`: A flag indicating whether it is possible to delete the firewall. A
  setting of TRUE indicates that the firewall is protected against deletion. Use this setting
  to protect against accidentally deleting a firewall that is in use. When you create a
  firewall, the operation initializes this flag to TRUE.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"UpdateToken"`: An optional token that you can use for optimistic locking. Network
  Firewall returns a token to your requests that access the firewall. The token marks the
  state of the firewall resource at the time of the request.  To make an unconditional change
  to the firewall, omit the token in your update request. Without the token, Network Firewall
  performs your updates regardless of whether the firewall has changed since you last
  retrieved it. To make a conditional change to the firewall, provide the token in your
  update request. Network Firewall uses the token to ensure that the firewall hasn't changed
  since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the firewall again to get a current copy
  of it with a new token. Reapply your changes as needed, then try the operation again using
  the new token.
"""
function update_firewall_delete_protection(
    DeleteProtection; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "UpdateFirewallDeleteProtection",
        Dict{String,Any}("DeleteProtection" => DeleteProtection);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_firewall_delete_protection(
    DeleteProtection,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "UpdateFirewallDeleteProtection",
        Dict{String,Any}(
            mergewith(
                _merge, Dict{String,Any}("DeleteProtection" => DeleteProtection), params
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_firewall_description()
    update_firewall_description(params::Dict{String,<:Any})

Modifies the description for the specified firewall. Use the description to help you
identify the firewall when you're working with it.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: The new description for the firewall. If you omit this setting, Network
  Firewall removes the description for the firewall.
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"UpdateToken"`: An optional token that you can use for optimistic locking. Network
  Firewall returns a token to your requests that access the firewall. The token marks the
  state of the firewall resource at the time of the request.  To make an unconditional change
  to the firewall, omit the token in your update request. Without the token, Network Firewall
  performs your updates regardless of whether the firewall has changed since you last
  retrieved it. To make a conditional change to the firewall, provide the token in your
  update request. Network Firewall uses the token to ensure that the firewall hasn't changed
  since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the firewall again to get a current copy
  of it with a new token. Reapply your changes as needed, then try the operation again using
  the new token.
"""
function update_firewall_description(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "UpdateFirewallDescription"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function update_firewall_description(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "UpdateFirewallDescription",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_firewall_policy(firewall_policy, update_token)
    update_firewall_policy(firewall_policy, update_token, params::Dict{String,<:Any})

Updates the properties of the specified firewall policy.

# Arguments
- `firewall_policy`: The updated firewall policy to use for the firewall.
- `update_token`: A token used for optimistic locking. Network Firewall returns a token to
  your requests that access the firewall policy. The token marks the state of the policy
  resource at the time of the request.  To make changes to the policy, you provide the token
  in your request. Network Firewall uses the token to ensure that the policy hasn't changed
  since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the firewall policy again to get a current
  copy of it with current token. Reapply your changes as needed, then try the operation again
  using the new token.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: A description of the firewall policy.
- `"DryRun"`: Indicates whether you want Network Firewall to just check the validity of the
  request, rather than run the request.  If set to TRUE, Network Firewall checks whether the
  request can run successfully, but doesn't actually make the requested changes. The call
  returns the value that the request would return if you ran it with dry run set to FALSE,
  but doesn't make additions or changes to your resources. This option allows you to make
  sure that you have the required permissions to run the request and that your request
  parameters are valid.  If set to FALSE, Network Firewall makes the requested changes to
  your resources.
- `"FirewallPolicyArn"`: The Amazon Resource Name (ARN) of the firewall policy. You must
  specify the ARN or the name, and you can specify both.
- `"FirewallPolicyName"`: The descriptive name of the firewall policy. You can't change the
  name of a firewall policy after you create it. You must specify the ARN or the name, and
  you can specify both.
"""
function update_firewall_policy(
    FirewallPolicy, UpdateToken; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "UpdateFirewallPolicy",
        Dict{String,Any}("FirewallPolicy" => FirewallPolicy, "UpdateToken" => UpdateToken);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_firewall_policy(
    FirewallPolicy,
    UpdateToken,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "UpdateFirewallPolicy",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "FirewallPolicy" => FirewallPolicy, "UpdateToken" => UpdateToken
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_firewall_policy_change_protection(firewall_policy_change_protection)
    update_firewall_policy_change_protection(firewall_policy_change_protection, params::Dict{String,<:Any})

Modifies the flag, ChangeProtection, which indicates whether it is possible to change the
firewall. If the flag is set to TRUE, the firewall is protected from changes. This setting
helps protect against accidentally changing a firewall that's in use.

# Arguments
- `firewall_policy_change_protection`: A setting indicating whether the firewall is
  protected against a change to the firewall policy association. Use this setting to protect
  against accidentally modifying the firewall policy for a firewall that is in use. When you
  create a firewall, the operation initializes this setting to TRUE.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"UpdateToken"`: An optional token that you can use for optimistic locking. Network
  Firewall returns a token to your requests that access the firewall. The token marks the
  state of the firewall resource at the time of the request.  To make an unconditional change
  to the firewall, omit the token in your update request. Without the token, Network Firewall
  performs your updates regardless of whether the firewall has changed since you last
  retrieved it. To make a conditional change to the firewall, provide the token in your
  update request. Network Firewall uses the token to ensure that the firewall hasn't changed
  since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the firewall again to get a current copy
  of it with a new token. Reapply your changes as needed, then try the operation again using
  the new token.
"""
function update_firewall_policy_change_protection(
    FirewallPolicyChangeProtection; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "UpdateFirewallPolicyChangeProtection",
        Dict{String,Any}(
            "FirewallPolicyChangeProtection" => FirewallPolicyChangeProtection
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_firewall_policy_change_protection(
    FirewallPolicyChangeProtection,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "UpdateFirewallPolicyChangeProtection",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}(
                    "FirewallPolicyChangeProtection" => FirewallPolicyChangeProtection
                ),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_logging_configuration()
    update_logging_configuration(params::Dict{String,<:Any})

Sets the logging configuration for the specified firewall.  To change the logging
configuration, retrieve the LoggingConfiguration by calling DescribeLoggingConfiguration,
then change it and provide the modified object to this update call. You must change the
logging configuration one LogDestinationConfig at a time inside the retrieved
LoggingConfiguration object.  You can perform only one of the following actions in any call
to UpdateLoggingConfiguration:    Create a new log destination object by adding a single
LogDestinationConfig array element to LogDestinationConfigs.   Delete a log destination
object by removing a single LogDestinationConfig array element from LogDestinationConfigs.
 Change the LogDestination setting in a single LogDestinationConfig array element.   You
can't change the LogDestinationType or LogType in a LogDestinationConfig. To change these
settings, delete the existing LogDestinationConfig object and create a new one, using two
separate calls to this update operation.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"LoggingConfiguration"`: Defines how Network Firewall performs logging for a firewall.
  If you omit this setting, Network Firewall disables logging for the firewall.
"""
function update_logging_configuration(; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "UpdateLoggingConfiguration"; aws_config=aws_config, feature_set=SERVICE_FEATURE_SET
    )
end
function update_logging_configuration(
    params::AbstractDict{String}; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "UpdateLoggingConfiguration",
        params;
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_rule_group(update_token)
    update_rule_group(update_token, params::Dict{String,<:Any})

Updates the rule settings for the specified rule group. You use a rule group by reference
in one or more firewall policies. When you modify a rule group, you modify all firewall
policies that use the rule group.  To update a rule group, first call DescribeRuleGroup to
retrieve the current RuleGroup object, update the object as needed, and then provide the
updated object to this call.

# Arguments
- `update_token`: A token used for optimistic locking. Network Firewall returns a token to
  your requests that access the rule group. The token marks the state of the rule group
  resource at the time of the request.  To make changes to the rule group, you provide the
  token in your request. Network Firewall uses the token to ensure that the rule group hasn't
  changed since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the rule group again to get a current copy
  of it with a current token. Reapply your changes as needed, then try the operation again
  using the new token.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"Description"`: A description of the rule group.
- `"DryRun"`: Indicates whether you want Network Firewall to just check the validity of the
  request, rather than run the request.  If set to TRUE, Network Firewall checks whether the
  request can run successfully, but doesn't actually make the requested changes. The call
  returns the value that the request would return if you ran it with dry run set to FALSE,
  but doesn't make additions or changes to your resources. This option allows you to make
  sure that you have the required permissions to run the request and that your request
  parameters are valid.  If set to FALSE, Network Firewall makes the requested changes to
  your resources.
- `"RuleGroup"`: An object that defines the rule group rules.   You must provide either
  this rule group setting or a Rules setting, but not both.
- `"RuleGroupArn"`: The Amazon Resource Name (ARN) of the rule group. You must specify the
  ARN or the name, and you can specify both.
- `"RuleGroupName"`: The descriptive name of the rule group. You can't change the name of a
  rule group after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"Rules"`: A string containing stateful rule group rules specifications in Suricata flat
  format, with one rule per line. Use this to import your existing Suricata compatible rule
  groups.   You must provide either this rules setting or a populated RuleGroup setting, but
  not both.   You can provide your rule group specification in Suricata flat format through
  this setting when you create or update your rule group. The call response returns a
  RuleGroup object that Network Firewall has populated from your string.
- `"Type"`: Indicates whether the rule group is stateless or stateful. If the rule group is
  stateless, it contains stateless rules. If it is stateful, it contains stateful rules.
  This setting is required for requests that do not include the RuleGroupARN.
"""
function update_rule_group(UpdateToken; aws_config::AbstractAWSConfig=global_aws_config())
    return network_firewall(
        "UpdateRuleGroup",
        Dict{String,Any}("UpdateToken" => UpdateToken);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_rule_group(
    UpdateToken,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "UpdateRuleGroup",
        Dict{String,Any}(
            mergewith(_merge, Dict{String,Any}("UpdateToken" => UpdateToken), params)
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end

"""
    update_subnet_change_protection(subnet_change_protection)
    update_subnet_change_protection(subnet_change_protection, params::Dict{String,<:Any})

# Arguments
- `subnet_change_protection`: A setting indicating whether the firewall is protected
  against changes to the subnet associations. Use this setting to protect against
  accidentally modifying the subnet associations for a firewall that is in use. When you
  create a firewall, the operation initializes this setting to TRUE.

# Optional Parameters
Optional parameters can be passed as a `params::Dict{String,<:Any}`. Valid keys are:
- `"FirewallArn"`: The Amazon Resource Name (ARN) of the firewall. You must specify the ARN
  or the name, and you can specify both.
- `"FirewallName"`: The descriptive name of the firewall. You can't change the name of a
  firewall after you create it. You must specify the ARN or the name, and you can specify
  both.
- `"UpdateToken"`: An optional token that you can use for optimistic locking. Network
  Firewall returns a token to your requests that access the firewall. The token marks the
  state of the firewall resource at the time of the request.  To make an unconditional change
  to the firewall, omit the token in your update request. Without the token, Network Firewall
  performs your updates regardless of whether the firewall has changed since you last
  retrieved it. To make a conditional change to the firewall, provide the token in your
  update request. Network Firewall uses the token to ensure that the firewall hasn't changed
  since you last retrieved it. If it has changed, the operation fails with an
  InvalidTokenException. If this happens, retrieve the firewall again to get a current copy
  of it with a new token. Reapply your changes as needed, then try the operation again using
  the new token.
"""
function update_subnet_change_protection(
    SubnetChangeProtection; aws_config::AbstractAWSConfig=global_aws_config()
)
    return network_firewall(
        "UpdateSubnetChangeProtection",
        Dict{String,Any}("SubnetChangeProtection" => SubnetChangeProtection);
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end
function update_subnet_change_protection(
    SubnetChangeProtection,
    params::AbstractDict{String};
    aws_config::AbstractAWSConfig=global_aws_config(),
)
    return network_firewall(
        "UpdateSubnetChangeProtection",
        Dict{String,Any}(
            mergewith(
                _merge,
                Dict{String,Any}("SubnetChangeProtection" => SubnetChangeProtection),
                params,
            ),
        );
        aws_config=aws_config,
        feature_set=SERVICE_FEATURE_SET,
    )
end


text:
using KeywordCalls
using Test, Pkg

f(nt::NamedTuple{(:c,:b,:a)}) = nt.a^3 + nt.b^2 + nt.c
@kwcall f(c,b,a)

struct Foo{N,T}
    nt::NamedTuple{N,T}
end

@kwstruct Foo(a,b)

@testset "KeywordCalls.jl" begin
    @testset "Functions" begin
        # @test @inferred f(1, 2, 3) == 32
        @test @inferred f(a=1, b=2, c=3) == 8
        @test @inferred f((a=1, b=2, c=3)) == 8
    end

    @testset "Constructors" begin
        @test @inferred Foo((b=1,a=2)).nt == (a=2,b=1)
    end
end

if isfile("./Precompile2/Manifest.toml")
    rm("./Precompile2/Manifest.toml")
end

Pkg.activate("./Precompile2")
Pkg.develop(PackageSpec(path="./Precompile1"))

using Precompile2

@testset "caching with precompilation" begin
    @test Precompile2.test() == (a=2, b=1)
end

ext: jl


text:
#=
sensemap-sim.jl
Simulate coil sensitivity maps
2019-06-18, Jeff Fessler, University of Michigan
=#

export ir_mri_sensemap_sim

#using MIRT: jim, image_geom

using SpecialFunctions: ellipk, ellipe
using Test: @test, @inferred
using Plots: Plot, plot, plot!, gui, contour!, scatter!, quiver, quiver!,
		clibrary, Arrow
	clibrary(:misc)

"""
    (smap,info) = ir_mri_sensemap_sim(...)

Simulate 2D or 3D sensitivity maps for sensitivity-encoded MRI based on
grivich:00:tmf http://doi.org/10.1119/1.19461

This code makes maps for multiple coils,
but does not model coupling between coils,
so most likely it is an approximation at best.

option
- `dims::Dims`		image size; default (64, 64)
- `dx::Real`		pixel/voxel dimension; default: 3
- `dy::Real`		pixel/voxel dimension; default: `dx`
- `dz::Real`		""
- `ncoil::Int`		# of coils total; default 4
- `nring::Int`		# of rings of coils; default 1
- `rcoil::Real`		coil radius; default `dx * nx / 2 * 0.50`
- `dz_coil`			ring spacing in z; default `nz*dz/nring`
			(3D geometry is a cylinder)
- `coil_distance::Real`		distance of coil center from isocenter
	for central ring of coils as a multiple of FOVx,
	where `FOVx=nx*dx`; default 1.2
- `orbit::Real`			default 360 [degrees]
- `orbit_start::Union{Real,AbstractVector{<:Real}} = 0` scalar or `nring` [degrees]
- `scale::Symbol`
  + `:none` (default)
  +	`ssos_center` make SSoS of center = 1

out
- `smap	[dims ncoil]`	simulated sensitivity maps (complex!)
- `info::NamedTuple`	geometry information for plots

All length parameters must have same units (e.g., mm or cm)

Matlab notes:
- 2005-6-20, Jeff Fessler and Amanda Funai, University of Michigan
- 2014-08-19 JF more testing, verifying phase is correct
- 2014-09-09 modified for 3D by Mai Le
- 2016-05-03 JF fixes
"""
function ir_mri_sensemap_sim( ;
		dims::Dims = (64,64), # 2D default
		dx::Real = 3,
		dy::Real = dx,
		dz::Real = 3,
		ncoil::Int = 4,
		nring::Int = 1,
		rcoil::Real = dx * dims[1] / 2 * 0.5,
		dz_coil::Real = ((length(dims) == 3) ? dims[3] : 1) * dz / nring,
		coil_distance::Real = 1.2, # multiplies fov/2
		orbit::Real = 360,
		orbit_start::Union{Real,AbstractVector{<:Real}} = 0,
		scale::Symbol = :none, # or :ssos_center
		chat::Bool = false,
	)

	(length(dims) < 2 || length(dims) > 3) && throw("2D or 3D only")
	nx = dims[1]
	ny = dims[2]
	nz = (length(dims) == 3) ? dims[3] : 0

	coils_per_ring = round(Int, ncoil / nring)
	ncoil != nring * coils_per_ring && throw("nring must be divisor of ncoil")

	(smap, info) = ir_mri_sensemap_sim_do(
			nx, ny, nz,
			dx, dy, dz,
			ncoil, coils_per_ring, rcoil, dz_coil,
			orbit, orbit_start, coil_distance, chat)

	scale_center = (nz == 0) ?
		1 / sqrt(sum(abs.(smap[round(Int,nx/2),round(Int,ny/2),:].^2))) :
		1 / sqrt(sum(abs.(smap[round(Int,nx/2),round(Int,ny/2),round(Int,nz/2),:].^2)))

	if scale === :ssos_center
		smap *= Float32(scale_center)
	elseif scale != :none
		throw("scale $scale")
	end

	return (smap, info)
end

"""
    (smap, info) = ir_mri_sensemap_sim_do()
"""
function ir_mri_sensemap_sim_do(nx, ny, nz,
		dx, dy, dz, ncoil, ncoilpr, rcoil, dz_coil,
		orbit, orbit_start, coil_distance, chat)

	nring = Int(ncoil / ncoilpr)
	rlist = Float32(rcoil) * ones(Float32, ncoilpr, nring) # coil radii

	zerof = (arg...) -> zeros(Float32, arg...)
	plist = zerof(ncoilpr, nring, 3) # position of coil center [x y z]
	nlist = zerof(ncoilpr, nring, 3) # normal vector (inward) from coil center
	olist = zerof(ncoilpr, nring, 3) # unit vector orthogonal to normal vector in x-y
	ulist = zerof(ncoilpr, nring, 3) # upward vector

	if length(orbit_start) == 1
		orbit_start = repeat([orbit_start], nring)
	elseif length(orbit_start) != nring
		throw("bad orbit_start length")
	end

	# cylindrical coil configuration, like abdominal coils
	alist = deg2rad.(orbit) * (0:(ncoilpr-1)) / ncoilpr # coil angles [radians]
	z_ring = ((1:nring) .- (nring+1)/2) * dz_coil
	for ir = 1:nring
		for ic = 1:ncoilpr
			phi = alist[ic] + deg2rad(orbit_start[ir])
			Rad = max(nx/2 * dx, ny/2 * dy) * coil_distance
			plist[ic,ir,:] = [Rad * [cos(phi), sin(phi)]; z_ring[ir]]
			nlist[ic,ir,:] = -[cos(phi), sin(phi), 0*z_ring[ir]] # cylinder
			olist[ic,ir,:] = [-sin(phi), cos(phi), 0]
			ulist[ic,ir,:] .= [0, 0, 1]
		end
	end

	# object coordinates
	x = Float32.(((1:nx) .- (nx+1)/2) * dx)
	y = Float32.(((1:ny) .- (ny+1)/2) * dy)
	z = (nz > 0) ? Float32.(((1:nz) .- (nz+1)/2) * dz) : [0]
	(xx, yy, zz) = ndgrid(x,y,z)

	smap = zeros(ComplexF32, nx, ny, max(nz,1), ncoilpr, nring)
	for ir = 1:nring
		for ic=1:ncoilpr
			# rotate coordinates to correspond to coil orientation
			zr =	(xx .- plist[ic,ir,1]) .* nlist[ic,ir,1] +
					(yy .- plist[ic,ir,2]) .* nlist[ic,ir,2] +
					(zz .- plist[ic,ir,3]) .* nlist[ic,ir,3]
			xr =	xx .* nlist[ic,ir,2] - yy .* nlist[ic,ir,1]
			yr = zz .- plist[ic,ir,3] # translate along object z axis

#=
			# show coordinates
			jim(x, y, xr) #, xlabel x, ylabel y
			jim(x, y, zr)
=#

			# compute sensitivity vectors in coil coordinates
			tmp = ir_mri_smap1.(xr, yr, zr, rlist[ic,ir])
			sx = [p[1] for p in tmp]
			sy = [p[2] for p in tmp]
			sz = [p[3] for p in tmp]

			# coil response depends on tranverse magnetization only?
			# todo: unsure if this should depend on sy and ulist in 3D
				bx = sz * nlist[ic,ir,1] + sx * olist[ic,ir,1]
				by = sz * nlist[ic,ir,2] + sx * olist[ic,ir,2]
			#	bz = sz * nlist[ic,ir,3] + sx * olist[ic,ir,3]
			smap[:,:,:,ic,ir] = complex.(bx, by)

			if chat && nz == 0 # see field components
				tmp = sqrt.(sx.^2 + sz.^2)
				(xx,yy) = ndgrid(x,y)
				plot(jim(x, y, sx, "sx"),
					jim(x, y, sy, "sy"),
					jim(x, y, sz, "sz"),
					quiver(xx[:], yy[:], title="(sx,sy)",
						quiver=((sx./tmp)[:], (sz./tmp)[:])),
					)
				prompt()
			end

			if chat && nz == 0 # see final field components vs phase
				(xx,yy) = ndgrid(x,y)
				bb = sqrt.(bx.^2 + by.^2)
				jim(x, y, angle.(smap[:,:,1,ic,1]), "phase", color=:hsv)
				quiver!(xx[:], yy[:], title="(bx,by)",
						quiver=((bx./bb)[:], (by./bb)[:]))
				prompt()
			end
		end
	end

	smap *= rlist[1] / Float32(2*pi) # trick: scale so maximum is near unity
	smap = nz == 0 ?  reshape(smap, nx, ny, ncoil) :
		reshape(smap, nx, ny, nz, ncoil)

	info = (x=x, y=y, z=z, dx=dx, dy=dy, dz=dz,
		nlist=nlist, plist=plist, rlist=rlist, olist=olist, ulist=ulist,
		nring=nring, ncoilpr=ncoilpr, rcoil=rcoil)
	return smap, info
end

"""
    ir_mri_sensemap_sim_show3()
shows coil geometry but not the 3D smap
"""
function ir_mri_sensemap_sim_show3(smap, x, y, z, dx, dy, dz,
	nlist, plist, rlist, olist, ulist, nring, ncoilpr, rcoil)

	pcolor = ['c', 'g', 'r']
	pcolor = i -> pcolor[1+rem(i,3)]

	ir_plot3_cube(x,y,z)
	scatter!(plist[:,:,1], plist[:,:,2], plist[:,:,3], label="") # coil centers

#=
	# coil normals - todo: 3d quiver not yet working
	tmp1 = reshape(plist, :, 3)
	tmp2 = reshape(nlist, :, 3)
	quiver!(tmp1[:,1], tmp1[:,2], tmp1[:,3],
		quiver=(tmp2[:,1], tmp2[:,2], tmp2[:,3]), label="3d")
	prompt()
=#

	if true # coils
		for ir = 1:nring
			for ic = 1:ncoilpr
				tmp = LinRange(0, 2*pi, 50)
				tmp = cos.(tmp) * olist[ic,ir,:]' + sin.(tmp) * ulist[ic,ir,:]'
				tmp = repeat(plist[ic,ir,:]', size(tmp,1), 1) + rcoil * tmp
				plot!(tmp[:,1], tmp[:,2], tmp[:,3], label="")
			#	patch(tmp[:,1], tmp[:,2], tmp[:,3], pcolor(ir),
			#		edgecolor=:none, facealpha=0.5)
			end
		end
	end
	plot!()
end

"""
    ir_plot3_cube(x,y,z)
"""
function ir_plot3_cube(x,y,z)
	x1 = x[1]
	x2 = x[end]
	y1 = y[1]
	y2 = y[end]
	z1 = z[1]
	z2 = z[end]
	x = [x1,x2,x2,x1,x1,x1,x2,x2,x1,x1]
	y = [y1,y1,y2,y2,y1,y1,y1,y2,y2,y1]
	z = [z1,z1,z1,z1,z1,z2,z2,z2,z2,z2]
	plot(x,y,z, label="", xlabel="x", ylabel="y", zlabel="z")
end

"""
    ir_mri_sensemap_sim_show2()
returns plot
"""
function ir_mri_sensemap_sim_show2(smap, x, y, dx, dy, nlist, plist, rlist)
	if ndims(smap) == 3
		(nx,ny,ncoil) = size(smap)
	elseif ndims(smap) == 4
		(nx,ny,nz,ncoil) = size(smap)
	else
		throw("unknown ndims(smap) = $(ndims(smap))")
	end

	pl = Array{Plot}(undef, ncoil, 3)
	clim = [0, maximum(abs.(smap))]
	xmax = maximum(abs.([x[:]; y[:]; plist[:,:,[1,2]][:]]))
	ymax = xmax
	for ic=1:ncoil
		tmp = smap[:,:,ic]
		p = jim(x, y, abs.(tmp), clim=clim, "Magnitude $ic")
		plot!(p, xlim=[-1,1]*1.1*xmax, xtick=(-1:1) * nx/2 * dx)
		plot!(p, ylim=[-1,1]*1.1*xmax, ytick=(-1:1) * nx/2 * dy)

		scatter!(p, [0], [0], marker=:o, label="", color=:green) # center
		scatter!(p, plist[:,:,1][:], plist[:,:,2][:],
			marker=:o, label="", color=:blue) # coil location
		xdir = nlist[ic,1,2]
		ydir = nlist[ic,1,1]
		r = rlist[ic,1]
		plot!(p, plist[ic,1,1].+r*xdir*[-1,1], plist[ic,1,2].+r*ydir*[1,-1],
			label="", color=:blue, linewidth=3) # coil
		pl[ic,1] = p

		ph = angle.(tmp) # show raw phase (understandable with hsv colormap)
		p = jim(x, y, ph, "Phase", clim=[-pi,pi], color=:hsv)
		plot!(p, xlim=[-1,1]*1.1*xmax, xtick=(-1:1) * nx/2 * dx)
		plot!(p, ylim=[-1,1]*1.1*xmax, ytick=(-1:1) * nx/2 * dy)
		pl[ic,2] = p
	end

	ssos = sqrt.(sum(abs.(smap).^2, dims=ndims(smap)))
	ssos = ssos / ssos[Int(end/2),Int(end/2)]

	p = jim(x, y, ssos, "SSoS (normalized)",
		#	xlim=[-1,1]*1.1*xmax,
			xtick=(-1:1) * nx/2 * dx,
			ytick=(-1:1) * ny/2 * dy)
	pl[1,3] = p

	if true # quiver plot for 1st coil
		bx = real(smap[:,:,1])
		by = imag(smap[:,:,1])
		(xx,yy) = ndgrid(x,y)
		p = quiver(xx[:], yy[:], quiver=(bx[:], by[:]),
				aspect_ratio = 1,
				arrow = Arrow(:simple,:head, 0.01, 0.01), # no effect!?
				title = "Field pattern in x-y plane")
		pl[2,3] = p
	end

	for ic=3:ncoil
		pl[ic,3] = plot(xaxis=:off,yaxis=:off,grid=:off) # kludge
	end

	return plot(pl[:]...)
end

"""
    ir_mri_smap_r(r, z)
function for testing near 0
"""
function ir_mri_smap_r(r, z)
	M = 4 * r / ((1 + r)^2 + z^2) # = k^2, see ellipke
	(K,E) = (ellipk.(M), ellipe.(M))
	return 2 * z / r * ((1 + r)^2 + z^2)^(-0.5) *
		((1 + r^2 + z^2) / ((1 - r)^2 + z^2) * E - K)
end

"""
    ir_mri_smap1()
based on grivich:00:tmf

for a circular coil in "x-y plane" of radius "a"

Note that coil x-y plane is not same as object x-y plane!

Returns `(i,j,k)` components of B vector for each `(x,y,z)` location
"""
function ir_mri_smap1(x, y, z, a)
	x = x / a # normalized units
	y = y / a
	z = z / a
	r = sqrt(x^2 + y^2)
	M = 4 * r / ((1 + r)^2 + z^2) # = k^2, see ellipke
	(K,E) = (ellipk.(M), ellipe.(M))

	# the following is B_z in eqn (18) in grivich:00:tmf
	# and same as eqn [10] in wang:00:dop to within constant scale factor
	smap_z = 2 * ((1 + r)^2 + z^2)^(-0.5) *
		(K + (1 - r^2 - z^2) / ((1 - r)^2 + z^2) * E)
	smap_z /= a

#=
	if any(r == 0) # test code to explore when r is near 0
		r0 = LinRange(0,5e-7,101)
		z0 = 0.4
		t0 = ir_mri_smap_r.(r0, z0)
		slope = 3*pi * z0 / ((1+z0^2)^2.5)
		plot(r0, t0); plot!(r0, slope * r0)
	end
=#

	# the following is B_r in eqn (17) in grivich:00:tmf
	smap_r = 2 * z / r * ((1+r)^2 + z^2)^(-0.5) *
		((1 + r^2 + z^2) / ((1-r)^2 + z^2) * E - K)

	if abs(r) < 1e-6
		smap_r = 3 * pi * z / ((1 + z^2).^2.5) * r
	end
	smap_r /= a

	(isnan(smap_r) || isnan(smap_z)) && throw("nan")

	smap_x = smap_r * (r == 0 ? 0 : x / r)
	smap_y = smap_r * (r == 0 ? 0 : y / r)

#	phi = atan2(y, x)
#	smap_x = smap_r * cos(phi)
#	smap_y = smap_r * sin(phi)

	return Float32(smap_x), Float32(smap_y), Float32(smap_z)
end

"""
    ir_mri_sensemap_sim_test0()
show ellipke
"""
function ir_mri_sensemap_sim_test0()
	@inferred ir_mri_smap_r(5e-7, 0.4)
	m = LinRange(0,1,101)
	(k,e) = (ellipk.(m), ellipe.(m))
	plot(yaxis=[0,3*pi/2])
	plot!(m, k, label="k")
	plot!(m, e, label="e")
	plot!(ytick=((0:3)*pi/2, ["0", "\\pi/2", "\\pi", "3\\pi/2"]))
end

"""
    ir_mri_sensemap_sim_test1()
test ir_mri_smap1 routine, cf Fig. 4 of grivich:00:tmf
"""
function ir_mri_sensemap_sim_test1()
	a = 1
	x = LinRange{Float32}(-2,2,99)
	y = LinRange{Float32}(-2,2,97)
#	zlist = Float32[0.001, 0.1, 0.2, 0.5, 1.0]
	zlist = Float32[0.1, 0.2, 0.5, 1.0]
#	(xx,yy,zz) = ndgrid(x, y, zlist)
	tmp = Iterators.product(x, y, zlist)
	tmp = [ir_mri_smap1(i[1], i[2], i[3], a) for i in tmp]
	smap_x = [p[1] for p in tmp]
	smap_y = [p[2] for p in tmp]
	smap_z = [p[3] for p in tmp]
#	(smap_x, smap_y, smap_z) = ir_mri_smap1.(xx, yy, zz, a)
	smap_b = @. sqrt(smap_x^2 + smap_y^2)
#	return plot(ir_mri_sensemap_sim_test1_show(smap_x, x, y, zlist, "x")...)
	return plot(layout=(4,length(zlist)),
			ir_mri_sensemap_sim_test1_show(smap_x, x, y, zlist, "x")...,
			ir_mri_sensemap_sim_test1_show(smap_y, x, y, zlist, "y")...,
			ir_mri_sensemap_sim_test1_show(smap_z, x, y, zlist, "z")...,
			ir_mri_sensemap_sim_test1_show(smap_b, x, y, zlist, "b")...,
		)
end

"""
    ir_mri_sensemap_sim_test1_show()
"""
function ir_mri_sensemap_sim_test1_show(smap, x, y, zlist, title)
	clim = [-20,20]
	nz = length(zlist)
	pl = Array{Plot}(undef, nz)
	for iz = 1:nz
		pl[iz] = jim(x, y, smap[:,:,iz],
			title=title, clim=clim, xtick=[-2,2], ytick=[-2,2])
		blim = (zlist[iz] < 0.5) ? [7,12,19] : [1,3,5]
		contour!(pl[iz], x, y, abs.(smap[:,:,iz])', levels=blim,
			color=:blue, colorbar_entry=false)
		contour!(pl[iz], x, y, abs.(smap[:,:,iz])', levels=[0,0].+0.001,
			color=:green, colorbar_entry=false)
		title == "b" && plot!(xlabel="z = $(zlist[iz])")
	end
	return pl
end

"""
    ir_mri_sensemap_sim_test2( ; chat)
return plot with 2D example
"""
function ir_mri_sensemap_sim_test2( ; chat::Bool=true)

	@test_throws String ir_mri_sensemap_sim(scale=:bug)
	@test_throws String ir_mri_sensemap_sim(nring=2, orbit_start = [1,2,3])

	(smap,t) = #@inferred # todo-i fails?
		ir_mri_sensemap_sim(dims=(32,32), scale=:ssos_center, chat=chat)

	if true # check rotational symmetry in 4-coil case
		for ic=2:4
			tmp = rotl90(smap[:,:,1], ic-1)
			@test isapprox(abs.(tmp), abs.(smap[:,:,ic]))
			p1 = angle.(tmp) .+ (ic-1) * pi/2 # add pi/2 to rotated
			p2 = angle.(smap[:,:,ic])
			tmp = ComplexF32.(cis.(p2 - p1))
			@test isapprox(tmp, ones(size(tmp))) # trick: equivs mod 2*pi
		end
	end

tmp = ir_mri_sensemap_sim_show2(smap,
	t.x, t.y, t.dx, t.dy, t.nlist, t.plist, t.rlist)
@show typeof(tmp)

	return ir_mri_sensemap_sim_show2(smap,
		t.x, t.y, t.dx, t.dy, t.nlist, t.plist, t.rlist)
end

"""
    ir_mri_sensemap_sim_test3( ; chat)
return plot that illustrates 3D sense maps
"""
function ir_mri_sensemap_sim_test3( ; chat::Bool=false)
	nring = 3
	ncoil = 4 * nring
	ig = image_geom(nx=16, ny=14, nz=10, fov=200, dz=20, mask=:circ) # 20cm fov
#	ig = image_geom(nx=72, ny=48, nz=12, fov=22, zfov=10) % michelle

	(smap,t) = #@inferred # todo-i fails
		ir_mri_sensemap_sim(dims=(ig.nx, ig.ny, ig.nz),
			dx=ig.dx, dz=ig.dz,
			orbit_start = 1*[0,45,0],
			rcoil=70, nring=nring, ncoil=ncoil, chat=chat)

	if true
		tmp = smap .* repeat(ig.mask, 1,1,1,ncoil)
		jim(ncol=ig.nz, tmp, abswarn=false)
		chat && prompt()
		tmp = permutedims(tmp, [1,3,2,4]) # [nx nz ny ncoil] z cuts are smooth
		jim(ncol=ig.ny, tmp, abswarn=false)
		chat && prompt()
		jim(ncol=1, tmp[:,:,round(Int,end/2),:], abswarn=false)
		chat && prompt()
	end

	ir_mri_sensemap_sim_show3(smap, t.x, t.y, t.z, t.dx, t.dy, t.dz,
			t.nlist, t.plist, t.rlist, t.olist, t.ulist,
			t.nring, t.ncoilpr, t.rcoil)
end

"""
    ir_mri_sensemap_sim(:test)
self test
"""
function ir_mri_sensemap_sim(test::Symbol)
	test != :test && throw(ArgumentError("test $test"))

	ir_mri_sensemap_sim_test0() # ellipk
	prompt()
	ir_mri_sensemap_sim_test1() # basic test
	prompt()
	ir_mri_sensemap_sim_test2() # 2d test
	prompt()
	ir_mri_sensemap_sim_test3() # 3d test
	prompt()

#=
	@test typeof(ir_mri_sensemap_sim_test0()) <: Plots.Plot # ellipk
	@test typeof(ir_mri_sensemap_sim_test1()) <: Plots.Plot # basic test
	@test typeof(ir_mri_sensemap_sim_test2()) <: Plots.Plot # 2d test
	@test typeof(ir_mri_sensemap_sim_test3()) <: Plots.Plot # 3d test
=#
	true
end

#= for plotting
ir_mri_sensemap_sim_test3(chat=true)
ir_mri_sensemap_sim_test3(chat=true)
=#
#@test ir_mri_sensemap_sim(:test)


text:
using ProgressMeter
using Random
using LinearAlgebra

include("layerForProp.jl")

"""
    perform the chained forward propagation using recursive calls

    input:
    X := input of the forward propagation
    cLayer := output layer
    cnt := an internal counter used to cache the layers was performed
           not to redo it again

    returns:
    A := the output of the last layer

    for internal use, it set again the values of Z and A in each layer
        to be used later in back propagation and add one to the layer
        forwCount value when pass through it
"""
function chainForProp!(X, cLayer::Layer, cnt::Integer=-1; kwargs...)
    if cnt<0
        cnt = cLayer.forwCount+1
    end

    if cLayer isa Input
        if cLayer.forwCount < cnt
            layerForProp!(cLayer, X; kwargs...)
        end #if cLayer.forwCount < cnt
        return nothing
    elseif isa(cLayer, AddLayer) #if typeof(cLayer)==AddLayer
        if cLayer.forwCount < cnt
            for prevLayer in cLayer.prevLayer
                chainForProp!(X, prevLayer, cnt; kwargs...)
            end
            layerForProp!(cLayer; kwargs...)
        end #if cLayer.forwCount < cnt

        return nothing
    else #if cLayer.prevLayer==nothing
        if cLayer.forwCount < cnt
            chainForProp!(X, cLayer.prevLayer, cnt; kwargs...)
            layerForProp!(cLayer; kwargs...)
        end #if cLayer.forwCount < cnt
        return nothing
    end #if cLayer.prevLayer!=nothing

end #function chainForProp!

export chainForProp!

"""
    predict Y using the model and the input X and the labels Y
    inputs:
        model := the trained model
        X := the input matrix
        Y := the input labels to compare with

    output:
        a Dict of
        "Yhat" := the predicted values
        "Yhat_bools" := the predicted labels
        "accuracy" := the accuracy of the predicted labels
"""
function predictBatch(
    model::Model,
    X::Array,
    Y=nothing,
    )
    chainForProp!(X, model.outLayer)
    Ŷ = model.outLayer.A
    T = eltype(Ŷ)
    outLayer = model.outLayer
    actFun = outLayer.actFun
    # if isbool(Y)
    return probToValue(eval(:($actFun)), Ŷ, labels=Y)

end #predict

function predict(
    model::Model,
    X_In::AbstractArray,
    Y_In=nothing;
    batchSize = 32,
    printAcc = true,
    useProgBar = false,
    GCInt = 5,
    noBool = false,
    )

    outLayer, lossFun, α = model.outLayer, model.lossFun, model.α
    Costs = []

    N = ndims(X_In)
    T = eltype(X_In)
    m = size(X_In)[end]
    # c = size(Y_train)[end-1]
    nB = m ÷ batchSize
    N = ndims(X_In)
    axX = axes(X_In)[1:end-1]
    Y = nothing
    if Y_In != nothing
        axY = axes(Y_In)[1:end-1]
    end
    if useProgBar
        p = Progress((m % batchSize != 0 ? nB+1 : nB), 0.1)
    end

    Ŷ_out = Array{T,N}(undef,repeat([0],N)...)
    accuracy = []
    @simd for j=1:nB
        downInd = (j-1)*batchSize+1
        upInd   = j * batchSize
        X = X_In[axX..., downInd:upInd]
        if Y_In != nothing
            Y = Y_In[axY..., downInd:upInd]
        end
        Ŷ, acc = predictBatch(model, X, Y)
        # Ŷ_out = cat(Ŷ_out, Ŷ, dims=1:N)
        if acc != nothing
            push!(accuracy, acc)
        end
        if useProgBar
            update!(p, j, showvalues=[("Instances $m", j*batchSize)])
        end #if useProgBar
        # X = Y = nothing
        Ŷ = nothing
        # if j%GCInt == 0
        #     Base.GC.gc()
        # end
    end

    if m % batchSize != 0
        downInd = (nB)*batchSize+1
        X = X_In[axX..., downInd:end]
        if Y_In != nothing
            Y = Y_In[axY..., downInd:end]
        end
        Ŷ, acc = predict(model, X, Y)

        Ŷ_out = cat(Ŷ_out, Ŷ, dims=1:N)
        if acc != nothing
            push!(accuracy, acc)
        end
        # X = Y = nothing
        Ŷ = nothing
        # Base.GC.gc()
        update!(p, nB+1, showvalues=[("Instances $m", m)])
    end

    accuracyM = nothing
    if !(isempty(accuracy))
        accuracyM = mean(accuracy)
    end
    if noBool
        Ŷ_out = nothing
    end

    return Ŷ_out, accuracyM

end #function predict(
    # model::Model,
    # X_In::AbstractArray,
    # Y_In=nothing;
    # batchSize = 32,
    # printAcc = true,
    # useProgBar = false,
    # )

export predict

"""
    return true if the array values are boolean (ones and zeros)
"""
function isbool(y::Array{T}) where {T}
    return iszero(y[y .!= one(T)])
end

### back propagation

include("layerBackProp.jl")

"""

    inputs:
    X := is a (nx, m) matrix
    Y := is a (c,  m) matrix
    model := is the model to perform the back propagation on
    cLayer := is an internal variable to hold the current layer
    cnt := is an internal variable to count the step of back propagation currently on

    output:
    nothing

"""
function chainBackProp!(X,Y,
                       model::Model,
                       cLayer::L=nothing,
                       cnt = -1;
                       tMiniBatch::Integer=-1, #can be used to perform both back and update params
                       kwargs...,
                       ) where {L<:Union{Layer,Nothing}}
    if cnt < 0
        cnt = model.outLayer.backCount+1
    end

    if cLayer==nothing
        layerBackProp!(model.outLayer, model; labels=Y, kwargs...)

        if tMiniBatch > 0
            layerUpdateParams!(model, model.outLayer, cnt; tMiniBatch=tMiniBatch, kwargs...)
        end

        chainBackProp!(X,Y,model, model.outLayer.prevLayer, cnt; tMiniBatch=tMiniBatch, kwargs...)

    elseif cLayer isa AddLayer
        layerBackProp!(cLayer, model; kwargs...)

        if tMiniBatch > 0
            layerUpdateParams!(model, cLayer, cnt; tMiniBatch=tMiniBatch, kwargs...)
        end

        if cLayer.backCount >= cnt #in case layerBackProp did not do the back
                                     #prop becasue the next layers are not all
                                     #done yet
            for prevLayer in cLayer.prevLayer
                chainBackProp!(X,Y,model, prevLayer, cnt; tMiniBatch=tMiniBatch, kwargs...)
            end #for
        end
    else #if cLayer==nothing
        layerBackProp!(cLayer, model; kwargs...)

        if tMiniBatch > 0
            layerUpdateParams!(model, cLayer, cnt; tMiniBatch=tMiniBatch, kwargs...)
        end

        if cLayer.backCount >= cnt #in case layerBackProp did not do the back
                                     #prop becasue the next layers are not all
                                     #done yet
            if !(cLayer isa Input)
                chainBackProp!(X,Y,model, cLayer.prevLayer, cnt; tMiniBatch=tMiniBatch, kwargs...)
            end #if cLayer.prevLayer == nothing
        end
    end #if cLayer==nothing

    return nothing
end #backProp

export chainBackProp!

###update parameters

include("layerUpdateParams.jl")

function chainUpdateParams!(model::Model,
                           cLayer::L=nothing,
                           cnt = -1;
                           tMiniBatch::Integer = 1) where {L<:Union{Layer,Nothing}}

    if cnt < 0
        cnt = model.outLayer.updateCount + 1
    end

    if cLayer==nothing
        layerUpdateParams!(model, model.outLayer, cnt, tMiniBatch=tMiniBatch)
        chainUpdateParams!(model, model.outLayer.prevLayer, cnt, tMiniBatch=tMiniBatch)

    elseif cLayer isa AddLayer
        #update the AddLayer updateCounter
        if cLayer.updateCount < cnt
            cLayer.updateCount += 1
        end
        for prevLayer in cLayer.prevLayer
            chainUpdateParams!(model, prevLayer, cnt, tMiniBatch=tMiniBatch)
        end #for
    else #if cLayer==nothing
        layerUpdateParams!(model, cLayer, cnt, tMiniBatch=tMiniBatch)
        if !(cLayer isa Input)
            chainUpdateParams!(model, cLayer.prevLayer, cnt, tMiniBatch=tMiniBatch)
        end #if cLayer.prevLayer == nothing
    end #if cLayer==nothing

    return nothing
end #function chainUpdateParams!

export chainUpdateParams!

"""
    Repeat the trainging (forward/backward propagation)

    inputs:
    X_train := the training input
    Y_train := the training labels
    model   := the model to train
    epochs  := the number of repetitions of the training phase
    ;
    kwarg:
    batchSize := the size of training when mini batch training
    printCostsIntervals := the interval (every what to print the current cost value)
    useProgBar := (true, false) value to use prograss bar

"""
function train(
               X_train,
               Y_train,
               model::Model,
               epochs;
               batchSize = 64,
               printCostsInterval = 0,
               useProgBar = false,
               embedUpdate = true,
               metrics::Array{Symbol,1} = [:accuracy, :cost],
               )

    outLayer, lossFun, α = model.outLayer, model.lossFun, model.α
    Costs = []

    m = size(X_train)[end]
    c = size(Y_train)[end-1]
    nB = m ÷ batchSize
    shufInd = randperm(m)
    N = ndims(X_train)
    axX = axes(X_train)[1:end-1]
    axY = axes(Y_train)[1:end-1]
    if useProgBar
        p = Progress(epochs, 1)
    end
    accuracy = []
    avgCost = 0.0
    avgAcc = 0.0
    for i=1:epochs
        minCosts = [] #the costs of all mini-batches
        minAcc = []
        for j=1:nB
            downInd = (j-1)*batchSize+1
            upInd   = j * batchSize
            batchInd = shufInd[downInd:upInd]
            X = X_train[axX..., batchInd]
            Y = Y_train[axY..., batchInd]

            if :accuracy in metrics
                ŷ, acc = predict(model, X, Y; noBool = true, batchSize = batchSize)
                push!(minAcc, acc)
                avgAcc = mean([avgAcc, acc])
            else
                chainForProp!(X,
                              model.outLayer)
            end

            a = model.outLayer.A
            if :cost in metrics
                minCost = sum(eval(:($lossFun($a, $Y))))/batchSize

                if lossFun==:binaryCrossentropy
                    minCost /= c
                end #if lossFun==:binaryCrossentropy

                push!(minCosts, minCost)
                avgCost = mean([avgCost, minCost])
            end

            if embedUpdate
                chainBackProp!(X,Y,
                               model;
                               tMiniBatch = j)
            else
                chainBackProp!(X,Y,
                               model;
                               tMiniBatch = -1)

                chainUpdateParams!(model; tMiniBatch = j)
            end #if embedUpdate
            if useProgBar
                if :accuracy in metrics && :cost in metrics
                    update!(p, i; showvalues=[(:Epoch, i), ("Instances ($m)", j*batchSize), (:Accuracy, avgAcc), (:Cost, avgCost)])
                elseif :accuracy in metrics
                    update!(p, i; showvalues=[(:Epoch, i), ("Instances ($m)", j*batchSize), (:Accuracy, avgAcc)])
                elseif :cost in metrics
                    update!(p, i; showvalues=[(:Epoch, i), ("Instances ($m)", j*batchSize), (:Cost, avgCost)])
                else
                    update!(p, i; showvalues=[(:Epoch, i), ("Instances ($m)", j*batchSize)])
                end
            end
            # chainUpdateParams!(model; tMiniBatch = j)

        end #for j=1:nB iterate over the mini batches

        if m%batchSize != 0
            downInd = (nB)*batchSize+1
            batchInd = shufInd[downInd:end]
            X = X_train[axX..., batchInd]
            Y = Y_train[axY..., batchInd]

            if :accuracy in metrics
                ŷ, acc = predict(model, X, Y; noBool = true, batchSize = size(X)[end])
                push!(minAcc, acc)
                avgAcc = mean([avgAcc, acc])

            else
                chainForProp!(X,
                              model.outLayer)
            end

            if :cost in metrics
                a = model.outLayer.A
                minCost = sum(eval(:($lossFun($a, $Y))))/size(X)[end]

                if lossFun==:binaryCrossentropy
                    minCost /= c
                end #if lossFun==:binaryCrossentropy

                push!(minCosts, minCost)
            end

            if embedUpdate
                chainBackProp!(X,Y,
                               model;
                               tMiniBatch = nB+1)
            else
                chainBackProp!(X,Y,
                               model;
                               tMiniBatch = -1)

                chainUpdateParams!(model; tMiniBatch = nB+1)
            end #if embedUpdate

            # chainUpdateParams!(model; tMiniBatch = nB+1)
        end

        push!(accuracy, mean(minAcc))
        push!(Costs, mean(minCosts))
        if printCostsInterval>0 && i%printCostsInterval==0
            println("N = $i, Cost = $(Costs[end])")
        end

        if useProgBar
            if useProgBar
                if :accuracy in metrics && :cost in metrics
                    update!(p, i; showvalues=[(:Epoch, i), ("Instances ($m)", m), (:Accuracy, avgAcc), (:Cost, avgCost)])
                elseif :accuracy in metrics
                    update!(p, i; showvalues=[(:Epoch, i), ("Instances ($m)", j*batchSize), (:Accuracy, avgAcc)])
                elseif :cost in metrics
                    update!(p, i; showvalues=[(:Epoch, i), ("Instances ($m)", j*batchSize), (:Cost, avgCost)])
                else
                    update!(p, i; showvalues=[(:Epoch, i), ("Instances ($m)", j*batchSize)])
                end
            end
        end
    end

    # model.W, model.B = W, B
    return Costs
end #train

export train