require "sketchup.rb"



module AE



class Console



class FileObserver



def initialize(interval=2)
  @supported_events = [:created, :changed, :deleted]
  @observers = {}
  @timer = nil
  @interval = (interval.is_a?(Numeric) && interval > 0) ? interval : 2 # in seconds
end


def check_files
  @observers.each{ |path, hash|
    begin
      status = File.exists?(path)
      if status == true # whether it exists now
        ctime = File.stat(path).ctime.to_i
        if hash[:status] == false # whether it existed before
          # File exists but did not exist before → created
          hash[:created].call(path) if hash[:created]
        else
          # File exists but did not exist before → created
          hash[:changed].call(path) if hash[:changed] && hash[:ctime] < ctime
        end
        hash[:ctime] = ctime
      else
        # File does not exist but existed before → deleted
        hash[:deleted].call(path) if hash[:status] == true && hash[:deleted]
      end
      hash[:status] = status
    rescue Exception => e
      $stderr.write(e.message << $/ << e.backtrace.join($/) << $/)
    end
  }
end
private :check_files


def register(path, event, &block)
  raise ArgumentError unless path.is_a?(String) && @supported_events.include?(event) && block_given?
  # If this is the first registered event, we need to start the timer.
  if @observers.empty?
    @timer = UI.start_timer(@interval, true) { check_files }
    check_files
  end
  # Register the event
  @observers[path] ||= {}
  @observers[path][event] = block
  status = File.exists?(path)
  @observers[path][:status] = status
  if status == true
    @observers[path][:ctime] = File.stat(path).ctime.to_i
  end
end


def unregister(path, event=nil)
  if event
    @observers[path].delete(event)
  else # all events for that path
    @observers.delete(path)
  end
  # If no events are left, we don't need to check them.
  if @timer && @observers.empty?
    UI.stop_timer(@timer)
    @timer = nil
  end
end


def unregister_all
  @observers.clear
  if @timer
    UI.stop_timer(@timer)
    @timer = nil
  end
end


end



end # class Console



end # module AE
