require "devops-client/handler/handler"
require "devops-client/options/image_options"
require "devops-client/output/image"

class Image < Handler

  output_with Output::Image

  def initialize(host, def_options={})
    @host = host
    @options = def_options
  end

  def handle
    @options_parser = ImageOptions.new(ARGV, @options)
    @command, @options, @args = @options_parser.parse_options_for!
    extract_parameters
    case @command
    when :list
      list_handler
      output
    when :show
      show_handler
      output
    when :create
      create_handler
    when :delete
      delete_handler
    when :update
      update_handler
    end
  end

  def create_handler
    q = {}
    q[:provider] = options[:provider] || resources_selector.select_available_provider
    q[:provider_account] = options[:provider_account] || resources_selector.select_available_provider_account(q[:provider])["account_name"]
    image = resources_selector.select_available_provider_account_image(q[:provider], q[:provider_account])

    q["name"] = image["name"]
    q["id"] = image["id"]
    q["image_id"] = q["id"]

    q["remote_user"] = options[:ssh_username] || enter_parameter(I18n.t("handler.image.create.ssh_user") + ": ")

    json = JSON.pretty_generate(q)
    post_body "/image", json if question(I18n.t("handler.image.question.create")){puts json}
  end

  def list_handler
    path = "/images"
    params = {}
    params["provider"] = @provider if @provider
    params["account"] = @account if @account
    unless params.empty?
      path += "?" + params.map{|k,v| "#{k}=#{v}"}.join("&")
    end
    @list = get(path)
  end

  def provider_images provider, provider_account
    if provider == 'static'
      @options_parser.invalid_list_command
      abort()
    end

    @list = get("/provider/#{provider}/account/#{provider_account}/images")
  end

  def show_handler
    @show = get "/image/#{@image}"
  end

  def delete_handler
    delete "/image/#{@image}" if question(I18n.t("handler.image.question.delete", :name => @image))
  end

  def update_handler
    update_object_from_file "image", @image, @file
  end

end
