require "devops-client/handler/handler"
require "devops-client/options/script_options"
require "devops-client/output/script"

class Script < Handler

  output_with Output::Script

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

  def handle
    current_command = ARGV[1].to_sym
    @options, @args = @options_parser.parse_options_for!(current_command)
    case current_command
    when :list
      list_handler
      output
    when :delete
      delete_handler
    when :update
      update_handler
    when :command
      command_handler
    when :run
      run_handler
    end
  end

  def command_handler
    r = inspect_parameters @options_parser.command_params, @args[2], @args[3]
    unless r.nil?
      @options_parser.invalid_command
      abort(r)
    end
    post_chunk_body "/script/command/#{@args[2]}", @args[3], false
  end

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

  def add_handler
    r = inspect_parameters @options_parser.add_params, @args[2], @args[3]
    unless r.nil?
      @options_parser.invalid_add_command
      abort(r)
    end
    abort("File '#{@args[3]}' does not exist") unless File.exists?(@args[3])
    put_body "/script/#{@args[2]}", File.read(@args[3])
  end

  def delete_handler
    r = inspect_parameters @options_parser.delete_params, @args[2]
    unless r.nil?
      @options_parser.invalid_delete_command
      abort(r)
    end
    if question(I18n.t("handler.script.question.delete", :name => @args[2]))
      delete "/script/#{@args[2]}"
    end
  end

  def run_handler
    r = inspect_parameters @options_parser.run_params, @args[2], @args[3]
    unless r.nil?
      @options_parser.invalid_run_command
      abort(r)
    end
    q = {
      :nodes => @args[3..-1]
    }
    q[:params] = self.options[:params] unless self.options[:params].nil?
    post_chunk "/script/run/#{@args[2]}", q
  end

end
