# Copyright (C) 2001-2005 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 "singleton"
require "thread"

class AutoReload
  include Singleton

  def initialize
    @status = {}
    @thread = nil
    @debug = false
  end
  attr_accessor :debug

  def autoreload(interval)
    @thread = Thread.new {
      loop {
	begin
	  update
	rescue Exception
	  STDOUT.puts("reload: "+$!)
	end
	sleep interval
      }
    }
    @thread.abort_on_exception = true
  end

  private

  def update
    check_lib = [$0] + $"
    check_lib.each {|lib|
      check_lib(lib)
    }
  end

  def check_lib(lib)
    if @status[lib]
      file, mtime = @status[lib]
      return if ! FileTest.exist?(file) # file is disappered.
      curtime = File.mtime(file).to_i
      if mtime < curtime
	$stdout.puts "reload: \"#{file}\"" if @debug
	load file	# Load it.
	@status[lib] = [file, curtime]
      end
      return
    end

    check_path = [""] + $LOAD_PATH
    check_path.each {|path|
      file = File.join(path, lib)
      file = lib if path == "" # Check if the lib is a filename.
      if FileTest.exist?(file)
	@status[lib] = [file, File.mtime(file).to_i]
	return 
      end
    }

    raise "The library #{lib} is not found."
  end

  def get_status(file)
    if FileTest.exist?(file)
      return [file, File.mtime(file).to_i]
    end
    return nil
  end
end

def autoreload(interval, debug = false)
  ar = AutoReload.instance
  ar.debug = debug
  ar.autoreload(interval)
end
