#
# completiontable.rb
#
# Copyright (c) 2003 Minero Aoki <aamine@loveruby.net>
#
# This program is free software.
# You can distribute/modify this program under the terms of
# the GNU Lesser General Public License version 2 or later.
#

require 'refe/traceutils'

module ReFe

  class CompletionTable

    include TraceUtils

    def initialize( path, writeok = false )
      @path = path
      @writeok = writeok
      @cache = {}
      begin
        read_list(path).each do |i|
          @cache[i] = true
        end
      rescue Errno::ENOENT
      end
    end

    attr_reader :path

    def inspect
      "\#<#{self.class} path=#{@path}>"
    end

    def read_list( path )
      File.open(path) {|f|
          return f.readlines.map {|line| line.strip }
      }
    end
    private :read_list

    def list
      @cache.keys
    end

    def expand( re )
      trace "comp: pattern = #{re.inspect}"
      results = []
      @cache.each_key do |item|
        results.push item if re === item
      end
      if results.size < 20
        trace "comp: results = #{results.join(' ')}"
      else
        trace "comp: results = (too many candidates: #{results.size})"
      end
      results
    end

    def add( item )
      raise ArgumentError, 'database is not writable' unless @writeok
      @cache[item] = true
    end
    
    def flush
      raise ArgumentError, "database is readonly: path=#{@path}" unless @writeok
      begin
        File.open("#{@path}_tmp#{$$}", 'w') {|f|
            @cache.keys.sort.each do |i|
              f.puts i
            end
        }
        File.rename "#{@path}_tmp#{$$}", @path
      rescue
        begin
          File.unlink "#{@path}_tmp#{$$}"
        rescue Errno::ENOENT
          ;
        end
      end
    end
  
  end

end
