begin
  require 'active_support/core_ext/string/inflections'
  require 'active_support/core_ext/object/blank'
rescue LoadError
  $stderr.puts 'You need to install the "activesupport"-gem to make that library work.'
  exit 1 
end

require 'open3'

require 'fedux_org/stdlib/environment'
require 'fedux_org/stdlib/command/command_result'

module FeduxOrg
  module Stdlib
    module Command
      include Environment

      # Execute command
      #
      # @param [String] cmd
      #   the command 
      #
      # @param [Hash] options
      #   the options for command execution
      #
      # @option options [Hash] env ({])
      #   the environment variables for the command ('VAR' => 'CONTENT')
      #
      # @option options [String] stdin (nil)
      #   the string for stdin of the command
      #
      # @option options [TrueClass,FalseClass] binmode (false)
      #   should the stdin be read a binary or not
      #
      # @return [CommandResult]
      #   the result of the command execution
      #
      # @return [CommandResult]
      #   the result of the command execution
      def run_command(cmd,options={})
        opts = {
          env: nil,
          stdin: nil,
          binmode: false,
          working_directory: Dir.getwd,
        }.merge options

        env = opts[:env] || ENV.to_hash
        stdin = opts[:stdin] 
        binmode = opts[:binmode]
        working_directory = opts[:working_directory]

        result = CommandResult.new
        result.stdout, result.stderr, result.status = Open3.capture3(env, cmd, stdin_data: stdin, chdir: working_directory, binmode: binmode)

        result
      end

      # Search for command
      # @param [String] cmd
      #    name of command or path to command (will be reduced to basename and then searched in PATH)
      #
      # @param [Array,String] paths
      #   a string containing paths separated by "File::PATH_SEPARATOR" or an array of paths
      #
      # @param [Array,String] pathexts
      #   a string containing pathexts separated by ";" or an array of pathexts
      #   
      # @return [String] 
      #   path to command
      def which(cmd, paths=ENV['PATH'].split(File::PATH_SEPARATOR), pathexts=ENV['PATHEXT'].to_s.split( /;/ ) )
        return nil if cmd.blank?

        cmd = File.basename( cmd )
        pathexts = [''] if pathexts.blank?

        Array( paths ).each do |path|
          Array( pathexts ).each do |ext|
            exe = File.join(path, "#{cmd}#{ext.to_s}")
            return exe if File.executable? exe
          end
        end                                                                                                                                                        
        nil
      end
    end
  end
end