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

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

module Qwik
  class SiteMonitor
    def initialize(config, site)
      @config = config
      @site = site

      @buf = []
      @buf.extend(MonitorMixin)
      @empty_cond = @buf.new_cond
    end

    def shout(event)
      @buf.synchronize {
	@buf.push(event)
	@empty_cond.broadcast
      }
    end

    def listen
      index = @buf.length
      #qp index
      loop {
	@buf.synchronize {
	  #qp @empty_cond.count_waiters
	  @empty_cond.wait_while {
	    @buf[index].nil?
	  }
	  ev = @buf[index]
	  #qp "new event", ev
	  index += 1
	  yield(ev)
	}
      }
    end
  end
end

if $0 == __FILE__
  require "qwik/test-common"
  $debug = true
end

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

    def listen_one(monitor)
      monitor.listen {|ev|
	return ev
      }
    end

    def test_monitors
      monitor = @site.sitemonitor

      t1 = Thread.new {
	ev = listen_one(monitor)
	assert_equal(1, ev)
      }

      t2 = Thread.new {
	ev = listen_one(monitor)
	assert_equal(1, ev)
      }

      sleep 0.01
      monitor.shout(1)

      t1.join
      t2.join
    end
  end
end
