require "devops-client/handler/handler"
require "devops-client/options/user_options"
require "devops-client/output/user"

class User < Handler

  output_with Output::User

  def initialize(host, def_options={})
    @host = host
    @options = def_options
    @options_parser = UserOptions.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 :create
      create_handler
    when :delete
      delete_handler
    when :password
      password_handler
    when :email
      email_handler
    when :role_add
      role_add_handler
    when :role_delete
      role_delete_handler
    end
  end

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

  def create_handler
    q = {
      "id" => @user_name,
      "email" => @email
    }
    q["password"] = self.options[:new_password] || enter_password(@user_name)
    q["roles"] = resources_selector.select_available_roles

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

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

  def password_handler
    q = {
        "password" => enter_password(@user_name)
    }

    put "/user/#{@user_name}/password", q
  end

  def email_handler
    q = {
        "email" => @email
    }
    put "/user/#{@user_name}/email", q
  end

  def role_add_handler
    user = get("/user/#{@user_name}")
    q = resources_selector.select_available_roles(user["roles"])
    post "/user/#{@user_name}/roles/add", q
  end

  def role_delete_handler
    user = get("/user/#{@user_name}")
    q = resources_selector.select_user_roles(user["roles"])
    post "/user/#{@user_name}/roles/delete", q
  end

  def enter_password user
    print "Enter password for '#{user}': "
    password = ""
    begin
      system("stty -echo")
      password = STDIN.gets.strip
      puts
    ensure
      system("stty echo")
    end
    password
  end

end
