require "devops-client/handler/handler"
require "devops-client/handler/provider"
require "devops-client/options/stack_template_options"
require "devops-client/output/stack_template"
# require 'devops-client/helpers/select_available'

class StackTemplate < Handler

  output_with Output::StackTemplate

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

  def handle
    @command, @options, @args = @options_parser.parse_options_for!
    extract_parameters
    case @command
    when :list
      list_handler(@provider)
      output
    when :show
      show_handler
      output
    when :create
      create_handler
    when :delete
      delete_handler
    when :update_url
      update_url_handler
    when :update_available_parameters
      update_available_parameters_handler
    end
  end

  def create_handler
    q = {
      id: options[:id],
      provider: options[:provider],
      provider_account: options[:provider_account]
    }
    q[:provider] ||= resources_selector.select_available_provider(except: ['static'])
    q[:provider_account] ||= resources_selector.select_available_provider_account(q[:provider])['account_name']
    q[:id] ||= enter_parameter(I18n.t('handler.stack_template.create.id'))

    filepath = options[:template_file] || enter_parameter(I18n.t('handler.stack_template.create.template_file'))
    q[:template_body] = get_file_contents(filepath)

    if question(I18n.t('handler.stack_template.question.create')) { puts confirming_json(q) }
      post_body("/stack_template/#{q[:provider]}", JSON.pretty_generate(q))
    end
  end

  def list_handler(provider=nil)
    @list = if provider
      provider_stack_templates(provider)
    else
      get("/stack_templates")
    end
  end

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

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

  private

  def provider_stack_templates(provider)
    if Providers.has_functionality?(provider, :stack_templates)
      @list = get("/stack_templates/provider/#{provider}")
    else
      @options_parser.invalid_list_command
      abort()
    end
  end

  def confirming_json(hash)
    to_output = hash.dup
    to_output[:template_body] = to_output[:template_body][0..40] + '…'
    JSON.pretty_generate(to_output)
  end

end
