class ::Notify < File
  def initialize(file)
    super(file, 'a+')
    @first = self.first_line
  end

  def first
    unless @first
      self.rewind
      @first = self.first_line
    end

    @first
  end

  def shift
    self.flock(File::LOCK_EX)
    self.rewind
    data = self.read.sub(/^.*?#{Regexp.escape(self.first)}\n/, '')
    self.truncate(0)
    self.puts(data)
    self.flush
    self.flock(File::LOCK_UN)
    @first = self.first_line
    self
  end

  def first_line
    self.rewind
    nil while (line = self.gets.chop rescue "").empty? and (self.size - self.tell) > 0
    line.empty? ? nil : line
  end
end

configure :notify do |s|
  s.file = File.realpath(File.join(ENV['HOME'], '.notify'))
  s.notify = ::Notify.new(s.file)
  s.icon = Subtlext::Icon.new('notify.xbm')
  s.mouse = false
  s.watch(s.file)
end

helper do
  def mouse_over
    self.mouse = true
  end

  def mouse_out
    self.mouse = false
  end

  def mouse_over?
    self.mouse
  end

  def refresh
    if self.mouse_over?
      self.data = (self.notify.first ? self.notify.first : '')
    else
      self.data = "" + (self.notify.first ? self.icon : '')
    end
  end

  def skip_first
    self.notify.shift if self.mouse_over?
    self.refresh
  end
end

on :watch do |s|
  s.refresh
end

on :run do |s|
  s.refresh
end

on :mouse_over do |s|
  s.mouse_over
  s.refresh
end

on :mouse_out do |s|
  s.mouse_out
  s.refresh
end

on :mouse_down do |s|
  s.skip_first
end
