#! /usr/bin/env ruby

$LOAD_PATH.unshift "."

require "optparse"
require "pathname"
require "fileutils"
require "digest/md5"
require "nkf"
require "hiki/util"
require "hiki/config"
require 'hiki/db/ptstore'

FILE_NAME_MAX_SIZE = 255

def convert_info_db(data_path, input_encoding, output_encoding, nkf)

  info_db_path = data_path + "info.db"
  db = PTStore.new(info_db_path)

  db.transaction do
    db.roots.each do |d|
      db[d][:title] = encode(db[d][:title], input_encoding, output_encoding, nkf)
      db[d][:references].map! do |r|
        encode(r, input_encoding, output_encoding, nkf)
      end
    end
    db.roots.each do |d|
      d_new = Hiki::Util.escape(encode(Hiki::Util.unescape(d),
                                       input_encoding, output_encoding, nkf))
      db[d_new] = db[d]
      db.delete d if d_new != d
    end
    db.commit
  end
end

def encode(text, input_encoding, output_encoding, nkf)
  if nkf
    NKF.nkf("-m0 --ic=#{input_encoding} --oc=#{output_encoding}", text)
  else
    text.dup.encode!(output_encoding, input_encoding, :invalid => :replace, :undef => :replace)
  end
end

def main(argv)
  parser = OptionParser.new
  data_path = nil
  repository_type = "plain"
  database_type = "flatfile"
  input_encoding = nil
  output_encoding = nil
  nkf = false
  check_only = false
  parser.on("-D", "--data-directory=DIR", "Specify the data directory"){|dir|
    data_path = Pathname(dir).realpath
  }
  # TODO Do we need to handle repository type?
  # parser.on("-r", "--repository-type=[TYPE]",
  #           "Specify the repository type [plain, svn, git, hg] (default: plain") {|type|
  #   repository_type = type
  # }
  parser.on("-d", "--database-type=[TYPE]",
            "Specify the database type [flatfile] (default: flatfile") {|type|
    database_type = type
  }
  parser.on("-i", "--input-encoding=ENCODING", "Specify the input encoding"){|encoding|
    input_encoding = Encoding.find(encoding)
  }
  parser.on("-o", "--output-encoding=ENCODING", "Specify the output encoding"){|encoding|
    output_encoding  = Encoding.find(encoding)
  }
  parser.on("--nkf", "Use NKF (default: no)"){
    nkf = true
  }

  begin
    parser.parse!(argv)
  rescue
    STDERR.puts $!.class.to_s
    STDERR.puts $!.message
    exit 1
  end

  # require_relative "../hiki/repos/#{repository_type}"
  # repository_class = ::Hiki.const_get("Repos#{repository_type.capitalize}")
  require_relative "../hiki/db/#{database_type}"
  database_class = ::Hiki::const_get("HikiDB_#{database_type}")

  convert_info_db(data_path, input_encoding, output_encoding, nkf)
end

if __FILE__ == $0
  main(ARGV)
end
