require "devops-client/handler/handler"
require "devops-client/options/key_options"
require "json"
require "devops-client/output/key"

class Key < Handler

  output_with Output::Key

  def initialize(host, def_options={})
    @host, @options = host, def_options
    @options_parser = KeyOptions.new(ARGV, def_options)
  end

  def handle
    @command, @options, @args = @options_parser.parse_options_for!
    extract_parameters
    case @command
    when :list
      list_handler
      output
    when :delete
      delete_handler
    when :add
      add_handler
    end
  end

  def add_handler
    content = File.read(@file)
    q = {
      "key_name" => @key_name,
      "file_name" => File.basename(@file),
      "content" => content
    }
    json = JSON.pretty_generate(q)
    post_body "/key", json if question(I18n.t("handler.key.question.create")){puts json}
  end

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

  def list_handler
    @list = get("/keys")
  end

end
