# Copyright (C) 2003-2005 Kouichirou Eto, All rights reserved.

require "pathname"
$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/fsdb"

module Qwik
  class BackupDB
    def initialize(path)
      @backup_path = path+".backup"
    end

    def close
      # do nothing
    end

    def path(k, time) # k is String, t is Time
      t = time.to_i.to_s
      @backup_path+(t+"_"+k)
    end
    private :path

    def exist?(k, time)
      path(k, time).exist?
    end

    def get(k, time)
      path(k, time).open {|f| f.read }
    end

    def put(k, time, v)
      @backup_path.check_directory
      path(k, time).open("wb"){|f| f.print(v) }
    end
    alias set put

    def each_by_key(key)
      @backup_path.check_directory
      ar = []
      @backup_path.each_entry {|file|
	f = @backup_path+file
	next unless f.file?
	base = file.to_s
	if /\A([0-9]+)_#{key}\z/ =~ base # end with key ?
	  time = Time.at($1.to_i)
	  v = get(key, time)
	  ar << [v, time]
	end
      }

      ar.sort_by {|v, time|
	time
      }.each {|v, time|
	yield(v, time)
      }
    end
  end
end

if $0 == __FILE__
  require "test/unit"
  require "qwik/config"
  require "qwik/test-module-path"
  $debug = true
end

if $debug
  class TC_BackupDB < Test::Unit::TestCase
    def setup
      @config = Qwik::Config.new(true)
      @dir = "./test/".path
      @dir.setup
    end

    def teardown
      @dir.teardown
    end

    def test_backupdb
      path = @dir
      spath = @config.super_dir.path
      pagedb = Qwik::FileSystemDB.new(path, spath)
      pagedb.create("1")
      pagedb.put("1", Time.at(1), "t")

      budb = pagedb.backupdb
      assert_instance_of(Qwik::BackupDB, budb)

      budb.each_by_key("1") {|v, time|
	assert_instance_of(String, v)
	assert_instance_of(Time, time)
	s = budb.get("1", time)
	assert_instance_of(String, s)
	assert_equal(v, s)
      }

      #put
      #exist?
    end
  end
end
