require "magellan/cli"

require 'thor'
require 'active_support/core_ext/string/inflections'

module Magellan
  module Cli
    class Command < Base
      include Magellan::Cli::FileAccess

      class << self
        # override Thor::Base.start method
        def start(given_args = ARGV, config = {})
          # class_options verbose and version are defined in Magellan::Cli::Base
          if (ARGV == ["-v"] || ARGV == ["--version"])
            log_info(File.basename($0) << " " << Magellan::Cli::VERSION)
            exit(0)
          elsif ARGV.include?("-v") || ARGV.include?("--version")
            log_info(File.basename($0) << " " << Magellan::Cli::VERSION)
          end
          begin
            super(given_args, config)
          rescue Magellan::Cli::Error => e
            log_error(e.message)
            block_given? ? yield(e) : exit(1)
          rescue => e
            log_error("[#{e.class}] #{e.message}")
            log_verbose("  " << e.backtrace.join("\n  "), ARGV.include?("-V") || ARGV.include?("--verbose"))
            block_given? ? yield(e) : exit(1)
          end
        end

        # overwrite Magellan::Cli::Base.help method
        def help(shell, subcommand = false)
          super(shell, subcommand)

          shell.say
          shell.say "RESOURCES:"
          shell.say "  " << Resources::MAPPING.keys.join(", ")
          shell.say "  " << I18n.t(:for_more_detail, scope: [:command, :cmd_help], command: File.basename($0))
          shell.say
        end
      end

      Resources::MAPPING.each do |classname, name|
        desc "#{name} SUBCOMMAND ...ARGS", I18n.t(:manage_resource, scope: [:command, :cmd], resource: name.pluralize)
        subcommand name, ::Magellan::Cli::Resources.const_get(classname)
      end

      COMMAND_ORDER = %w[login] + Resources::MAPPING.values

      #desc "direct SUBCOMMAND ...ARGS", "Send request directly"
      #subcommand "direct", ::Magellan::Cli::Direct

      desc "login", I18n.t(:login, scope: [:command, :cmd])
      method_option :email,    aliases: "-e", desc: I18n.t(:email, scope: [:command, :cmd_login])
      method_option :password, aliases: "-p", desc: I18n.t(:password, scope: [:command, :cmd_login])
      def login
        unless email = options[:email]
          print "email: "
          email = STDIN.gets.strip
        end

        unless password = options[:password]
          print "password: "
          password = STDIN.noecho(&:gets).chomp
          puts ""
        end

        Magellan::Cli::Http.new.login!(email, password)
      end

      desc "info", I18n.t(:info, scope: [:command, :cmd])
      def info
        cli = Magellan::Cli::Login.new
        cli.check_login_auth!
        selections = load_selections || {}
        d = {"user" => cli.login_auth["email"] }
        Resources::MAPPING.each do |classname, name|
          klass = ::Magellan::Cli::Resources.const_get(classname)
          if val = selections[ klass.parameter_name ]
            d[name] = val["name"] ? val["name"] : val.inspect
          end
        end
        log_info YAML.dump(d)
      end

    end
  end
end