module Fuelcell
  module Parser
    # Handles short options that express their value without using a space like
    # -uroot where the short opt is -u and value is root
    class ShortOptNoSpaceHandler < BaseHandler
      # @param cmd [Fuelcell::Command]
      # @param args [Array] raw args from ARGV
      # @param opts [Hash] stores the found opts
      # @return [Boolean]
      def call(cmd, args, opts)
        arg = take_first_arg(args) do |text|
          !(text =~ /^-([a-zA-Z]{2,})$/).nil?
        end
        return false unless arg

        return true if handle_no_space_value(cmd, opts, args, arg)

        arg[0] = '' # remove the dash
        handle_cluster(cmd, opts, arg)

        true
      end

      private

      # we need to determine if this is a short opt with a value
      # smushed into it or a cluster of opts
      def handle_no_space_value(cmd, opts, args, arg)
        name  = "-#{arg[1]}"
        value = arg.slice(2, arg.size)
        opt   = cmd.find_opt(name)

        fail "#{name} is not a registered option" unless opt

        unless opt.flag?
          assign_opt_value(opts, opt, value, name)
          return true
        end
        false
      end

      def handle_cluster(cmd, opts, arg)
        cluster = arg.split('')
        cluster.each do |short|
          opt = cmd.find_opt("-#{short}")
          unless opt.flag?
            fail "-#{short} can not live in a cluster, it must be a flag"
          end
          found_opt_flag(opts, opt)
        end
      end
    end
  end
end
