#!/usr/bin/env ruby
require 'drb'
require 'logger'
require 'optparse'

require 'pry'

require File.expand_path('../../lib/onapp_cli/options', __FILE__)
require File.expand_path('../../lib/onapp_cli/client/drb_server', __FILE__)
require File.expand_path('../../lib/onapp_cli/client/virtual_machines', __FILE__)
require File.expand_path('../../lib/onapp_cli/client/templates', __FILE__)

include OnappCLI::Options

options do |opts|
  opts.banner = "  Usage: onapp command [options]"
  opts.separator ""
  opts.separator "Type: onapp help [command]"
  opts.separator "Commands: build_vm, start_vm, stop_vm, templates"
  
  opts.separator ""
  opts.separator "  \033[1mHelp\033[0m" 
  opts.on_tail("--help", "Show this message") do
  end
end

command = ARGV[0]
second_argument = ARGV[1]
case command
when nil, /^-/, "help"
  puts opts.to_s
  exit
when 'server'
  unless %w(start stop status restart).include?(second_argument)
    puts "Available arguments: start, stop, restart and status"
  else
    OnappCLI::Client::DRbServer.send(second_argument)
  end
  exit
when 'build_vm', 'build_virtual_machine'
  OnappCLI::Client::VirtualMachines.build_virtual_machine
when 'start_vm', 'startup_virtual_machine'
  OnappCLI::Client::VirtualMachines.start_virtual_machine
when 'stop_vm', 'stop_virtual_machine'
  OnappCLI::Client::VirtualMachines.stop_virtual_machine
when 'templates'
  unless %w(list install update remove).include?(second_argument)
    puts "Available arguments: list, install, update, remove"
  else
    OnappCLI::Client::Templates.send(second_argument)
  end
else
  puts "[Error] Unknown command '#{command}'"
  puts opts.to_s
  exit
end

def puts_select_list(list, attribute = nil)
  selected_item = ''

  puts "0 - exit"
  list.each_with_index do |item, index|
    puts "#{(index+1).to_s} - #{attribute.nil? ? item.to_s : item.send(attribute.to_sym)}"
  end

  while index = STDIN.gets.chomp do
    case index.to_i
      when 0
        exit
      when 1..(list.length + 1)
        selected_item = list[index.to_i-1]
        break
      else
        puts "Invalid template index. Try again:"
    end
  end

  selected_item
end