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

$LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
require "qwik/config"
require "qwik/memory"

module Qwik
  class SiteDB
    def initialize(config, site)
      @config = config
      @site = site
      @sitename = @site.sitename
      @path = @config.cache_dir
      @path = @path.sub(%r!\A/cygdrive/(\w)!){|a| $1+":" } # /cygdrive/c -> c:
      @file = @path+"/"+@sitename+".db"
      @db = nil
      open
    end

    def open
      require "sqlite"	# SQLite
      @db = ::SQLite::Database.new(@file, 0)
    end

    def table_exist?(table)
      @db.table_info(table) {|row|
	return true
      }
      false
    end
    
    def quote(org)
      ::SQLite::Database.quote(org)
    end

    def encode(org)
      ::SQLite::Database.encode(org)
    end

    def decode(org)
      ::SQLite::Database.decode(org)
    end

    def check_table(table)
      raise unless /\A[a-z]+\z/ =~ table
      quote(table) # make sure
    end

    def table_create(table)
      t = check_table(table)
      sql = <<"EOT"
create table #{t}
(
  id INTEGER PRIMARY KEY,
  key TEXT,
  value VARCHAR
);
create index idx_#{t}_key on #{t} ( key );
EOT
      @db.execute(sql)
    end

    def delete(t, k)
      t = check_table(t)
      k = quote(k)
      @db.execute("delete from #{t} where key='#{k}';")
    end

    def set(t, k, v)
      t = check_table(t)
      k = quote(k)
      delete(t, k) if get(t, k)
      v = encode(v)
      @db.execute("insert into #{t} values (NULL, '#{k}', '#{v}');")
    end

    def get(t, k)
      t = check_table(t)
      k = quote(k)
      v = @db.get_first_value("select value from #{t} where key='#{k}'" )
      return nil if v.nil?
      decode(v)
    end
  end
end
