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

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

module Qwik
  class SiteConfig
    def initialize(config, site)
      @config = config
      @site = site
      @default = default_config

      page = get_page

      @db = page.wikidb
    end

    # FIXME: Read default site config from super/_SiteConfig.txt
    def default_config
      {
	"open"		=> "false",
	"theme"		=> "qwikgreen",
	"sitename"	=> @config.default_hostname,
	"aid"		=> "q02-22", # amazon associate id
	"ml_life_time"	=> (60*60*24*31).to_s, # 1 month
	"reportmail"	=> "hourly",
	"reportfrom"	=> "",
	"titlelink"	=> "false",
	"redirect"	=> "false",
	"siteurl"	=> "",
      }
    end
    private :default_config

    def get_page
      k = "SiteConfig"
      return @site[k] if @site.exist?(k)
      k = "_SiteConfig"
      return @site[k] if @site.exist?(k)
      k = "_SiteConfig"
      return @site.create(k)
    end

    def [](k)
      v = @db[k]
      return @default[k] if v.nil?
      v
    end
  end
end

if $0 == __FILE__
  require "qwik/test-module-session"
  require "qwik/farm"
  $debug = true
end

if $debug
  class TC_SiteConfig < Test::Unit::TestCase
    include TestSession

    def test_siteconfig
      # test_open
      assert_equal(false, @site.is_open?)
      page = @site.create("_SiteConfig")
      page.store(":open:true")
      assert_equal(true, @site.is_open?)
      page.store(":open:false")
      assert_equal(false, @site.is_open?)
      @site.delete("_SiteConfig")
      assert_equal(false, @site.is_open?)

      # test_theme
      assert_instance_of(String, @site.siteconfig["theme"])
      page.store(":theme:qwik")

      # test_sitename
      assert_equal("example.com", @site.siteconfig["sitename"])
#      assert_equal("example.com/test", @site.title)
      page.store(":sitename:TestSite")
      assert_equal("TestSite", @site.siteconfig["sitename"])
      assert_equal("TestSite", @site.title)

      # test_title
      page = @site.create("TestPage")
      assert_equal("TestPage", page.get_title)
#      assert_equal("TestPage - TestSite", @site.title("TestPage"))

      page = @site.create("1")
      assert_equal("1", page.get_title)
#      assert_equal("1 - TestSite", @site.title("1"))
      page.store("* TestTitle")
#      assert_equal("TestTitle - TestSite", @site.title("1"))

      # test_url
      assert_equal("http://example.com/", @site.domainurl)
      assert_equal("http://example.com/test/", @site.url)
      assert_equal("http://example.com/test/1.html", @site.url("1"))
      assert_equal("test@example.com", @site.ml)
    end
  end
end
