require "devops-client/handler/handler"
require "devops-client/options/role_options"
require "devops-client/output/role"

class Role < Handler

  output_with Output::Role
  include InputUtils

  def initialize(host, def_options={})
    @host, @options = host, def_options
    @options_parser = RoleOptions.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 :show
      show_handler
      output
    when :create
      create_handler
    when :delete
      delete_handler
    when :policies
      policies_handler
      output
    end
  end

  def list_handler
    @list = get("/security/roles")
  end

  def show_handler
    @show = get("/security/role/#{@role_name}")
  end

  def policies_handler
    @list = get("/security/policies")
  end

  def create_handler
    q = {
      "name" => @role_name
    }
    q["description"] = options[:description] || enter_parameter(I18n.t("handler.role.create.description") + ": ")
    all = question(I18n.t("handler.role.question.all_policies"))
    if all
      q["policies"] = ["all"]
    else
      policies_handler

      q["policies"] = if options[:policies]
        #TODO: validation
        options[:policies]
      else
        @command = :policies
        select_items_from_table(I18n.t("handler.role.create.policies"), @list, outputter.table).map{|p| p["id"]}
      end
    end

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

  def delete_handler
    delete("/security/role/#{@role_name}") if question(I18n.t("handler.role.question.delete", role: @role_name))
  end

end
