# prime/engine/engine-personaldict.rb
# $Id: engine-personaldict.rb,v 1.3 2005/03/07 07:51:32 komatsu Exp $
#
# Copyright (C) 2004 Hiroyuki Komatsu <komatsu@taiyaki.org>
#     All rights reserved.
#     This is free software with ABSOLUTELY NO WARRANTY.
#
# You can redistribute it and/or modify it under the terms of 
# the GNU General Public License version 2.
#

require 'prime/engine/engine-sary'

$engine_class_name = 'PrimeEnginePersonalDict'

class PrimeEnginePersonalDict < PrimeEngineSary
  def initialize
    @dict_dir  = File::join2(PRIME_USER_DIR, 'work')
    @dict_name = 'personaldict'
    dict_file = @dict_dir + '/' + @dict_name
    @src_dir   = File::join2(PRIME_USER_DIR , 'dicts')
    Dir::ensure(@src_dir)

    super(dict_file)

    @name = "PersonalDict engine"
    @id   = "personaldict"
    @description = "PersonalDict engine"
  end

  def initialize_dict ()
    flag_create = false

    ## @dict_file is defined in the parent class PrimeEngineSary,
    ## its value should be @dict_dir + '/' + @dict_name.
    if File::exist?(@dict_file) then
      mtime = File::mtime(@dict_file)
    else
      ## The below mtime means a sentinel.
      mtime = Time::at(0)
    end

    Dir::foreach(@src_dir) { | src_dict |
      ## Matching the filename src_dict with (.dict|.skkdict|.cannadict)
      ## and comparing the timestamp with the index file.
      if src_dict =~ /dict$/ and 
          File::mtime(@src_dir + '/' + src_dict) > mtime then
        flag_create = true
        break
      end
    }

    ## FIXME: Move the following codes to prime-dict-convert.
    ## FIXME: <komatsu@taiyaki.org> (2004-02-06)
    if flag_create then
      tmp_dir  = @dict_dir + '/tmp'
      tmp_dict = tmp_dir + '/' + @dict_name
      Dir::ensure(@dict_dir)
      Dir::ensure(tmp_dir)
      File::delete(tmp_dict) if File::exist?(tmp_dict)

      Dir::foreach(@src_dir) {|src_dict|
        if src_dict =~ /\.dict$/ then
          format = 'prime'
        elsif src_dict =~ /\.skkdict$/ then
          format = 'skk'
        elsif src_dict =~ /\.cannadict$/ then
          format = 'canna'
        else
          next
        end
        system("#{PRIME_COMMAND_DICT_CONVERT} --quiet #{tmp_dict} " + \
               " --append --#{format} #{@src_dir}/#{src_dict}")
      }

      Dir::foreach(tmp_dir) {|file|
        if file.index(@dict_name) == 0 then
          File::rename(tmp_dir + '/' + file, @dict_dir + '/' + file)
        end
      }
      ## This might exec the command "prime-refresh".
      system("#{PRIME_COMMAND_REFRESH}")
    end

    refresh()
  end

  def refresh ()
    return unless File::exist?(@dict_file)

    @dict         = Sary::Searcher.new(@dict_file)
    @dict_literal = Sary::Searcher.new(@dict_file, @dict_file + "_literal.ary")
    @partdict     = Sary::Searcher.new(@dict_file + '-pos')
  end
end
