# Copyright 2015 Google Inc. All rights reserved.
#
# 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.
"""Creates an autoscaled IGM that will create VMs with a passed template.

This is normaly to be used with a Back-End service. It essentially allows you
to deploy IGM and AS combinations to X number of zones.
"""
import common
import default

# Specific properties for this component
# Inside the Zones dict
SIZE = default.SIZE
MAX_NUM = default.MAX_NUM
ZONE = default.ZONE

# Generic for all autoscaled_group created
PROJECT = default.PROJECT
VM_TEMPLATE = default.VM_TEMPLATE


def GenerateAutscaledGroup(context, zone_dict):
  """Generate one autoscaled_group resource Dict with a passed zone."""
  name = context.env['name']
  project = context.env[PROJECT]
  prop = context.properties
  zone = zone_dict[default.ZONE]
  zone_abbrv = common.ShortenZoneName(zone)
  as_name = common.AutoName(name, default.AUTOSCALER, zone_abbrv)
  base_name = name + '-' + default.AKA[default.INSTANCE]
  igm_name = common.AutoName(name, default.IGM, zone_abbrv)
  max_num = zone_dict[MAX_NUM]
  project = context.env[default.PROJECT]
  size = zone_dict[SIZE]
  vm_template = prop[VM_TEMPLATE]

  # pyformat: disable
  resource = [
      {
          'name': igm_name,
          'type': default.IGM,
          'properties': {
              'project': project,
              'zone': zone,
              'targetSize': size,
              'baseInstanceName': base_name,
              'instanceTemplate': vm_template
          }
      }, {
          'name': as_name,
          'type': default.AUTOSCALER,
          'properties': {
              'project': project,
              'zone': zone,
              'target': common.Ref(igm_name),
              'autoscalingPolicy': {
                  'maxNumReplicas': max_num
              }
          }
      }
  ]
  # pyformat: enable
  return resource


def GenerateNAutoscaledGroup(context):
  """Generates N groups of IGM and AUTOSCALER combinations.

  The groups are all the same except the zone in which they run. That is
  determined by the ZoneList property.

  Args:
    context: The DM PythonEvaluationContext

  Returns:
    list of resources to be deployed.
  """
  i_template = context.properties[default.VM_TEMPLATE]
  if not common.IsComputeLink(i_template):
    context.properties[VM_TEMPLATE] = common.GlobalComputeLink(
        context.env[default.PROJECT], 'instanceTemplates', i_template)
  replica_list = context.properties[default.REPLICAS]

  resource_list = []

  for zone_dict in replica_list:
    resource_list.extend(GenerateAutscaledGroup(context, zone_dict))
  return resource_list


def GenerateResourceList(context):
  """Returns list of resources generated by this module."""
  return GenerateNAutoscaledGroup(context)


@common.FormatErrorsDec
def GenerateConfig(context):
  """Generates YAML resource configuration."""
  return common.MakeResource(GenerateResourceList(context))
