require "devops-client/handler/deploy_envs/deploy_env"

class DeployEnvEc2 < DeployEnv

  NAME = "ec2"

  def initialize host, options, auth
    @host = host
    self.auth = auth
    self.options = options
  end

  def provider
    NAME
  end

  def fill obj
    super(obj) do |o|
      set_stack_template(o)
      set_flavor(o)
      set_image(o)
      vpc_id = set_subnets(o)
      set_groups(o, vpc_id)
      set_chef_env(o)
    end
  end

  def set_subnets d
    unless self.options[:subnets].nil?
      self.options[:subnets] = [ self.options[:subnets][0] ]
    end
    vpc_id = nil
    set_parameter d, :subnets do
      networks, networks_table = fetcher.fetch_with_table('network', self.provider)
      if networks.any?
        num = choose_number_from_list(I18n.t("handler.project.create.subnet.ec2"), networks, networks_table, -1)
        vpc_id = networks[num]["vpcId"] unless num == -1
        num == -1 ? [] : [ networks[num]["subnetId"] ]
      else
        []
      end
    end
    vpc_id
  end

  def set_groups d, vpc_id
    set_parameter d, :groups do
      groups = resources_selector.select_available_groups(provider: self.provider, vpc_id: vpc_id)
      groups.map{|t| t['id']}
    end
  end

  def set_chef_env(d)
    set_parameter d, :chef_env do
      enter_parameter('Chef environment: ')
    end
  end

  def set_stack_template(d)
    if question(I18n.t("handler.project.question.set_stack_template"))
      set_parameter d, :stack_template do
        resources_selector.select_available_stack_template(provider: 'ec2')
      end
    end
  end

end
