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

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

module Qwik
  class PeriodicThread
    def initialize(config, memory, time)
      @config, @memory = config, memory
      @logger = @memory[:logger]
      @time = time
    end

    def start
      loop {
	begin
	  process
	rescue Exception => e
	  qp e
	end
	sleep @time
      }
    end

    def process # abstract
    end
  end

  class SweepThread < PeriodicThread
    def initialize(config, memory)
      super(config, memory, 60*60) # 1hour
      @farm = @memory.farm
    end

    def process
      @farm.sweep
    end
  end
end

if $0 == __FILE__
  $LOAD_PATH << "../../lib" unless $LOAD_PATH.include?("../../lib")
  require "qwik/test-common"
  $debug = true
end

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

    def test_dummy
    end

    def nu_test_all
      @periodic = Qwik::Periodic.new(@config, @memory)
      # @periodic.time = 1 # for test, do it on every second.
      @periodic.time = 1000 # for test, do it on every second.

      t = Thread.new { @periodic.start }
      t.abort_on_exception = true

      @farm = @memory.farm
      @site = @farm.get_site("test")
      assert_equal(false, @site.inactive?)
      page = @site["_SiteConfig"]
      page.store(":ml_life_time:0") # die soon.

      sleep 2 # will run sweep

      @site = @farm.get_site("test")
      assert_equal(nil, @site)

      t.kill
    end
  end
end
