require "devops-client/handler/helpers/input_utils"
require "devops-client/handler/helpers/resources_selector"

class DeployEnv

  include InputUtils

  attr_accessor :options, :auth

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

  def set_parameter obj, key
    if self.options[key].nil?
      obj[key] = yield
    else
      obj[key] = self.options[key]
    end
  end

  def fill obj
    yield(obj) if block_given?

    set_users(obj)

    unless self.options[:run_list].nil?
      self.options[:run_list] = self.options[:run_list].split(",").map{|e| e.strip}
      abort("Invalid run list: '#{self.options[:run_list].join(",")}'") unless DeployEnv.validate_run_list(self.options[:run_list])
    end
    set_parameter obj, :run_list do
      set_run_list_cmd
    end

    unless self.options[:no_expires]
      set_parameter obj, :expires do
        s = enter_parameter_or_empty(I18n.t("options.project.create.expires") + ": ").strip
        s.empty? ? nil : s
      end
    end
  end

  def set_run_list_cmd
    res = nil
    begin
      res = get_comma_separated_list(I18n.t("options.project.create.run_list") + ": ")
    end until DeployEnv.validate_run_list(res)
    res
  end

  # flavors commands
  def set_flavor d
    set_parameter d, :flavor do
      resources_selector.select_available_flavor(provider: self.provider)
    end
  end

  def set_image d
    set_parameter d, :image do
      resources_selector.select_available_image(provider: self.provider)
    end
  end

  def set_users d
    set_parameter d, :users do
      Set.new(resources_selector.select_available_users)
    end
    d[:users].add(self.options[:username])
    d[:users] = d[:users].to_a
  end


  private

  def resources_selector
    @resources_selector ||= Helpers::ResourcesSelector.new(fetcher)
  end

  def fetcher
    @fetcher ||= Helpers::ResourcesFetcher.new(host: @host, handler_options: @options, auth: @auth)
  end


end
