# $Id: site.rb,v 1.42 2004/04/22 14:47:49 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, 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 GPL2.

require 'time'
require 'fileutils'
require 'qwik/config'
require 'qwik/util'
require 'qwik/page'
require 'qwik/ext_siteconfig'

module Qwik
  class Farm # bundle many sites to one object.
    def initialize(config)
      @config = config
      @data_dir = @config.data_dir
      @sites = {}
    end

    def exist?(s)
      get_site(s) != nil
    end

    def get_site(s)
      if (@data_dir.path+s).directory? # check the dir first
	if @sites[s].nil?
	  @sites[s] = Site.new(@config, s) # create new site
	end
      else
	@sites[s] = nil if @sites[s] # delete
      end
      @sites[s]
    end
  end

  class Site
    def initialize(config, sitename)
      @config = config
      @sitename = sitename
      @dir = @config.data_dir+'/'+sitename
      @pages = Pages.new(@config, @dir)

      @cache_path = @config.cache_dir.path
      @cache_path.mkdir if !@cache_path.directory?

      @hostname = @config.default_hostname
      @hostname = @sitename if @sitename =~ /\./ # external qwik site

      @plugin = nil
    end
    attr_reader :sitename
    attr_reader :dir, :pages
    attr_reader :cache_path
    attr_accessor :plugin

    def inspect()	"#<Site:"+@sitename+">";	end

    def [](k)		@pages[k];		end
    def create(k)	@pages.create(k);	end

    def domainurl()
      'http://'+@hostname+'/'
    end

    def url(k=nil)
      u = domainurl()
      u += @sitename+'/' unless @sitename == 'www' || @sitename =~ /\./
      u += self[k].url if k
      u
    end

    def ml()
      return 'info@'+@sitename if @sitename =~ /\./
      return @sitename+'@'+@hostname
    end

    private
    def site_title
      url().sub(%r|^http://|, '').sub(%r|/$|, '')
    end

    def page_title(pagename=nil)
      return nil if pagename.nil?
      page = self[pagename]
      return nil if page.nil?
      page.get_title
    end
  end
end
