#  Licensed under the Apache License, Version 2.0 (the "License"); you may
#  not use this file except in compliance with the License. You may obtain
#  a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#  License for the specific language governing permissions and limitations
#  under the License.

Namespaces:
  =: io.murano

Name: SharedIpRange
Extends: SharedIp

Properties:
  cidr:
    Contract: $.string().notNull()
    Usage: InOut


Methods:
  initialize:
    Body:
      - $._environment: $.find(Environment).require()


  deploy:
    Body:
      - If: not $.getAttr(deployed, false)
        Then:
          - $region: $.getRegion()
          - $reporter: $._environment.reporter

          - $.deployNetwork()
          - $networkData: $.network.describe()

          - $aapSubnetName: format('AllowedAddressPairsSubnet-{0}', id($))
          - $template:
              resources:
                $aapSubnetName:
                  type: 'OS::Neutron::Subnet'
                  properties:
                    enable_dhcp: false
                    network: $networkData.netId
                    cidr: $.cidr
              outputs:
                $aapSubnetName+'-cidr':
                  value:
                    get_attr: [$aapSubnetName, cidr]
                  description: format('Shared IP Range of group {0}', id($))

          - $region.stack.updateTemplate($template)

          - $region.stack.push()
          - $outputs: $region.stack.output()
          - $.cidr: $outputs.get(format('AllowedAddressPairsSubnet-{0}-cidr', id($)))
          - $.virtualIp: $outputs.get(format('AllowedAddressPairsSubnet-{0}-cidr', id($)))
          - $reporter.report($this, format('Shared IP Range allocated at {0}', $.cidr))
          - $.setAttr(deployed, true)


  getSharedIpRef:
    Body:
      - $aapSubnetName: format('AllowedAddressPairsSubnet-{0}', id($))
      - Return:
          get_attr: [$aapSubnetName, cidr]


  releaseResources:
    Body:
      - $region: $.getRegion()
      - $template: $region.stack.current()
      - $template.resources: $template.resources.delete(format('AllowedAddressPairsSubnet-{0}', id($)))
      - $template.outputs: $template.outputs.delete(format('AllowedAddressPairsSubnet-{0}-cidr', id($)))
      - $region.stack.setTemplate($template)
      - $region.stack.push()
      - $.cidr: null