# frozen_string_literal: true

require 'litany/resource'
require 'litany/mixins'

module Litany
  class InstanceGroup < MetaResource
    parent_resource :service
    include ServiceRoot
    include Taggable
    include Metable

    child_resource AutoScalingGroup, :auto_scaling_group
    child_resource AutoScalingLaunchConfiguration, :launch_configuration

    property :detailed_monitoring, true, [true, false], inherited: true
    property :device_prefix, 'sd', ['sd', 'xvd']
    property :ebs_optimized, true, [true, false], inherited: true
    property :group_size, 2, Integer
    property :instance_type, nil, [nil, String], inherited: true
    property :key_pair, nil, [nil, String, Symbol], inherited: true
    property :root_volume_size, 50, 4..16_384, inherited: true

    resource_reference Image, :image, inherited: true
    resource_reference InstanceProfile, :instance_profile, inherited: true

    resource_references ApplicationLoadBalancerTargetGroup, :target_group, required: false
    resource_references SecurityGroup, :security_group, inherited: true, required: false

    def finalize_resource
      auto_scaling_group.desired_size = group_size unless auto_scaling_group.set_desired_size?
      auto_scaling_group.max_size = group_size unless auto_scaling_group.set_max_size?
      auto_scaling_group.min_size = group_size unless auto_scaling_group.set_min_size?

      # Set Block Device Mapping sizes
      launch_configuration.root_volume_size root_volume_size
      launch_configuration.device_prefix device_prefix
    end

    def volume(*args, &block)
      launch_configuration.volume(*args, &block)
    end

    def default_tags
      {
          LitanyInstanceGroupName: self.name,
      }
    end
  end
end
