#!/usr/local/bin/ruby
#
# ShellCommandLineEditor.rb
#
#   $Author: hiroya $
#   $Date: 2000/11/23 01:53:10 $
#   Copyright (C) 2000 Hiroya KUBO
#

require "CommandLineEditor"
require "ShellExecutables"
require "ContextualExecutables"
require "UnixDirectoryClient"
require "StringUtil"

class RubyShell < CommandLineEditor

  include ShellExecutables

  PROMPT1 = ""
  PROMPT2 = " > "

  def initialize
    super
    getExecutables.update(getShellExecutables)
    getExecutables.update(ContextualExecutables.new.getContextualExecutables)
    @dir = UnixDirectoryClient.new
  end

  def prompt
    @term.print(PROMPT1).set(['blue','underline','bold']).print(Dir.pwd).reset.print(PROMPT2)  
  end

  def getMatchedFileNameList(path)
    candidates = []
    @dir.foreach(path.getDirectory) do |filename|
      if( path.getFileName == nil ||
	 filename.index(path.getFileName) == 0 )
	if( @dir.directory?(path.getDirectory+@dir.getSeparator+filename) )
	  candidates.push(filename+@dir.getSeparator)
	else
	  candidates.push(filename)
	end
      end
    end
    return candidates.sort
  end

  def getCompletingPathList(key)
    reg_name = @dir.getRegulatedName(@dir.getContextualName(key))
    path = DirPath.new(reg_name,
		       @dir.dirname(reg_name),
		       @dir.basename(reg_name))

    if(! @dir.directory?(path.getDirectory) ||
	( ! @dir.directory?(reg_name) && key =~/\/$/ ))
      return [nil]
    end

    list = getMatchedFileNameList(path)

    if( @dir.directory?(path.getName) &&
       (key == "" || key =~ /\/$/ ))
      path = DirPath.new(path.getName, path.getName, "")
      list = getMatchedFileNameList(path)
    end

    if(list.size == 1 &&
       @dir.directory?(path.getName) &&
       key != "" && key !~ /\/$/)
      return [path, [path.getFileName+@dir.getSeparator()]]
    else
      return [path, list]
    end
  end

  def getCompletingList(key)
    path, list = getCompletingPathList(key)
    if(path != nil && path.getFileName != nil)
      list = StringUtil.removePrefix(path.getFileName, list)
    end
    return list
  end

  def showCompletingList(array)
    key = @line.getCurrentWord
    if(array!=nil)
      array.each{|arg|
	@term.print(key).print(arg).newline
      }
    end
  end

end


class DirPath
  def initialize(name=nil, dir=nil, filename=nil)
    @name = name
    @dir = dir
    @filename = filename
  end
  def getName
    return @name
  end
  def getFileName
    return @filename
  end
  def getDirectory
    return @dir
  end
end


RubyShell.new.doit
